<?php
$db_id = mysqli_connect($db_host, $db_user, $db_pass, $db_name )
or die("Could not connect to DB.");
//mysqli_select_db($db_name, $db_id)
//or die("Database not found.");
//time difference; gets for how much the mysql server time is ahead, compared to the http server time;
$query="SELECT timediff(now(), '".date("Y-m-d H:i:s")."')";
$result=mysqli_query($db_id, $query);
$tdif=mysqli_fetch_row($result); $tdif=explode(":", $tdif[0]);
if ($tdif[0][0]=="-") {$tdif[0]=abs($tdif[0]); $tdif[3]="-";}
else $tdif[3]="+"; $tdif=" ".$tdif[3]." interval ".$tdif[0]." hour ".$tdif[3]." interval ".$tdif[1]." minute ".$tdif[3]." interval ".$tdif[2]." second";

/*if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
 else {$imgs="default/"; $fimgs="1/";}*/
//setting untuk grafik

if (isset($_SESSION["user"][0]))
{
	$faction=faction($_SESSION["user"][10]);
	$imgs=$_SESSION["user"][13];
	$fimgs=$faction[2];
}
else
{
	$imgs="default/";
	$fimgs="1/";
}

function showqueue($tasktotal, $tasklink,$taskcount,$taskitem,$taskduration,$taskupdateurl)
{
	global $lang;
	$_GET["town"]=clean($_GET["town"]);
	$output = '
	<div class="row clearfix">
		<div class="col-md-4 column">'.ads(1,"queue").'</div>
		<div class="col-md-8 column">'.queuebuilding().queueacademy().queueunit().queueweap().'</div>
	</div>';
	$tasks='<li class="list-group-item">No active task</li>';
	if ($tasktotal)
	{
		if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
		else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
		$tasks = "";
		$imgpath = $imgs.$fimgs;
					for ($i=0; $i<$tasktotal; $i++)
					{
					$tasks .= '<li class="list-group-item"> '.img("r06.png",$lang['duration']).' <span class="label label-success" id="'.$i.'">'.$taskduration[$i].' </span>';
					$tasks .= '  <a href="'.$tasklink[$i].'">'.img("cancel.png","Cancel").'</a>';
					$tasks .= '  <b>'.$taskcount[$i]." x ".$taskitem[$i].'</b>';
					$tasks .= "\n<script type='text/javascript'> var id=new Array(50); timer('".$i."', 'town.php?".$_GET["town"]."'); </script></li>";

					//$tasks .= "\n<script type='text/javascript'> var id=new Array(50); timer('".$i."', '".$taskupdateurl[$i]."'); </script></li>";

					}
					
	}
	
	$body=$output;
	return PageSection("queue", 12, $lang["unitUpgQueue"], $body,"Total tasks :".$tasktotal);//$output;
}
function queueunit($afifio="")
{
	global $lang;
//	$units = $afifio["faction"];
$faction = faction ( $_SESSION ["user"] [10] );
$units = units ( $faction [0] );
$output = '<li class="list-group-item">No unit under training</li>';
	//$wq = get_w ( $_GET ["town"] );
	$uq = get_u ( $_GET ["town"] );
		$cnt = "";	$li = ""; $no = ""; $na = ""; $du = ""; $ret = "";
		if (count ( $uq )) 
		{
			$output = "";
			//echo "Unit training queue:</br>";
			for($i = 0; $i < count ( $uq ); $i ++) {
				$cnt ++;
				$li [$i] = "cancel_u.php?town=" . $_GET ["town"] . "&type=" . $uq [$i] [1];
				$no [$i] = $uq [$i] [2];
				$na [$i] = $units [$uq [$i] [1]] [2];
				$du [$i] = $uq [$i] [0];
				$ret [$i] = "barracks.php?town=" . $_GET ["town"];
				$output .= "\n".'<li class="list-group-item"> '.img("r06.png",$lang['duration']).' <span class="label label-success" id="unit'.$i.'">'.$du[$i].' </span>';
					$output .= '  <a href="'.$li[$i].'">'.img("cancel.png","Cancel").'</a>';
					$output .= '  <b>'.$no[$i]." x ".$na[$i].'</b>';
					$output .= "\n<script type='text/javascript'> var id=new Array(50); timer('unit".$i."', '".$_SERVER['REQUEST_URI']."'); </script></li>";
									//	$output .= d($units[$i][0]);
			}
		//showqueue($tasktotal, $tasklink,$taskcount,$taskitem,$taskduration,$taskupdateurl)
		//$output .= showqueue ( $cnt, $li, $no, $na, $du, $ret );
		}

	$body='<ul class="list-group">'.$output.'</ul>';
return $body;
}
function queueweap($afifio="")
{
		global $lang;
//	$units = $afifio["faction"];
$faction = faction ( $_SESSION ["user"] [10] );
$weapons = weapons ( $_SESSION ["user"] [10] );
$output = '<li class="list-group-item">No weapon under production</li>';
	$wq = get_w ( $_GET ["town"] );
		$cnt = "";	$li = ""; $no = ""; $na = ""; $du = ""; $ret = "";
		if (count ( $wq )) 
		{
			$output = "";
			//echo "Unit training queue:</br>";
			for($i = 0; $i < count ( $wq ); $i ++) {
				$cnt ++;
				$li [$i] = "cancel_u.php?town=" . $_GET ["town"] . "&type=" . $wq [$i] [1];
				$no [$i] = $wq [$i] [2];
				$na [$i] = $weapons [$wq [$i] [1]] [2];
				$du [$i] = $wq [$i] [0];
				$ret [$i] = "washop.php?town=" . $_GET ["town"];
				$output .= "\n".'<li class="list-group-item"> '.img("r06.png",$lang['duration']).' <span class="label label-success" id="weapon'.$i.'">'.$du[$i].' </span>';
					$output .= '  <a href="'.$li[$i].'">'.img("cancel.png","Cancel").'</a>';
					$output .= '  <b>'.$no[$i]." x ".$na[$i].'</b>';
					$output .= "\n<script type='text/javascript'> var id=new Array(50); timer('weapon".$i."', '".$ret[$i]."'); </script></li>";
				//	$output .= d($weapons[$i][0]);
			}
		}

	$body='<ul class="list-group">'.$output.'</ul>';
return $body;
}
function queueacademy()
{
	
$faction = faction ( $_SESSION ["user"] [10] );
$units = units ( $faction [0] );
$upq=get_up($_GET["town"]);
$output = '<li class="list-group-item">No unit upgrade or research</li>';
		$cnt = "";	$li = ""; $no = ""; $na = ""; $du = ""; $ret = "";
		if (count ( $upq )) 
		{
			$output = "";
			//echo "Academy training queue:</br>";
			for($i = 0; $i < count ( $upq ); $i ++) 
			{
				$cnt ++;
				$li[$i] = "cancel_uup.php?town=".$_GET["town"]."&unit=".$upq[$i][1]."&tree=".$upq[$i][2];
				$no [$i] = $upq [$i] [2];
				$na[$i] = $units[$upq[$i][1]][2];
				$du [$i] = $upq [$i] [0];
				$ret [$i] = "academy.php?town=" . $_GET ["town"];
				$output .= "\n".'<li class="list-group-item"> '.img("r06.png",$lang['duration']).' <span class="label label-success" id="academy'.$i.'">'.$du[$i].' </span>';
					$output .= '  <a href="'.$li[$i].'">'.img("cancel.png","Cancel").'</a>';
					$output .= '  <b>'.$no[$i]." x ".$na[$i].'</b>';
					$output .= "\n<script type='text/javascript'> var id=new Array(50); timer('academy".$i."', '".$ret[$i]."'); </script></li>";
				}	
			}
	$body='<ul class="list-group">'.$output.'</ul>';
return $body;
}
function queuebuilding()
{
	global $lang;
$town=town($_GET["town"]);
$cq=get_c($_GET["town"]);
$buildings=buildings($_SESSION["user"][10]);
$land=explode("/", $town[13]);
	$data=explode("-", $town[8]); 
$output = '<li class="list-group-item">No building upgrade</li>';
$cnt = "";	$li = ""; $no = ""; $na = ""; $du = ""; $ret = "";
if (count($cq)) 
{

$output = ""; 
//	echo $lang['constQueue'].":</br>huh?";
		for ($i=0; $i<count($cq); $i++)
		{
			$name=explode("-", $buildings[$cq[$i][1]][2]);
			if ($cq[$i][2]>-1)
			{
				$s=1; $l=$land[$cq[$i][1]][$cq[$i][2]]+1;
			}
			else
			{
				$s=0; $l=$data[$cq[$i][1]]+1;
			}
//			echo "[<a class='q_link' href='cancel_c.php?town=".$_GET["town"]."&b=".$cq[$i][1]."&subB=".$cq[$i][2]."'>x</a>] ".$name[$s].", ".$lang['level']." ".$l." - <span id='cq".$i."'>".$cq[$i][0]."
//			</span><script type='text/javascript'> var id=new Array(50); timer('cq".$i."', 'town.php?town=".$_GET["town"]."'); </script></br>";
$output .= "\n".'<li class="list-group-item"> '.img("r06.png",$lang['duration']).' <span class="label label-warning" id="cq'.$i.'">'.$cq[$i][0].' </span>';
$output .= '  <a href="cancel_c.php?town="'.$_GET["town"].'"&b='.$cq[$i][1].'&subB='.$cq[$i][2].'">'.img("cancel.png","Cancel").'</a>';
$output .= '  <b>'." Upgrading ".$name[$s].'</b>';
$ret[$i] = 'town.php?town='.$_GET["town"];
$output .= "\n<script type='text/javascript'> var id=new Array(50); timer('cq".$i."', '".$ret[$i]."'); </script></li>";
		}
	}
	$body='<ul class="list-group">'.$output.'</ul>';
return $body;
}
function msg($msg)
{
	header("Location: msg.php?msg=".$msg);
}
function label($msg)
{
	$output = "";
	//$t = "<font face=\"Fixedsys\" color=\"red\">".$msg."</font>";
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	$output .= "\n<table class='cute'><tr>";
	$output .= "<td rowspan='2'><img src='".$imgpath."32alert.png' align='absmiddle''></td>";
	$output .= "<td width='100%' ><h2>Information</h2><hr></td>";
	$output .= "</tr><tr>";
	$output .= "<td>".$msg."</td>";
	$output .= "</tr></table>";
	return $output;
}
function findin($what,$list)
{
	for ($i = 0; $i < count($list); $i++)
	{
		if ($what == $list[$i])
		{
			return	1;
		}
	}
	return 0;
}




function buildingstandard($town,$to,$lim, $buildings,$faction,$c_status,$iconwhat = "info.png",$givewhat="")
{
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}

	$imgpath = $imgs.$fimgs;
	$r=$faction[3];
	$lim = explode ( "-", $town [11] );
	$data=explode("-", $town[8]);
	$res=explode("-", $town[10]);
	$prod=explode("-", $town[9]);
	$toicon = "b".$to.".png";
	$upgrade = "";
				$dur=explode("-", $buildings[$to][6]);
				$upk=explode("-", $buildings[$to][7]);
				$cost=explode("-", $buildings[$to][4]);
				$out=explode("-",$buildings[$to][5]);
/*	if ($data[$to] == "10")
		{
			//building maximum, jadi data takder
			$out[10] = "0";
			$dur[10] = "0";
			$upk[10] = "0";
			$lim[10] = "0";
			$dur[10] = "0:00";
			
		}*/
				$dur[$data[$to]]=explode(":", $dur[$data[$to]]);
				$weaps=explode("-", $town[6]);
				$co = cost(
				floor($cost[0]*pow($r, $data[$to])),
				floor($cost[1]*pow($r, $data[$to])),
				floor($cost[2]*pow($r, $data[$to])),
				floor($cost[3]*pow($r, $data[$to])),
				floor($cost[4]*pow($r, $data[$to])),
				($dur[$data[$to]][0]*$lim[4]/100)."
				:".($dur[$data[$to]][1]*$lim[4]/100),
				"upk.png", $lang['upkeep'],
				$upk[$data[$to]],
				$iconwhat,
				$givewhat,
				$out[$data[$to]]);
				
				//d($lim);
		//$output .= buildingheader($to,$buildings,$data,$lim,$town,$upgrade);
	/*	
	<div class="col-md-2 column">
		<div class="thumbnail">
			<img  alt="140x140" src="'.$imgs.$fimgs.'b'.$to.'.png">
			<div class="caption">
				<h3>Level '.$data[$to].'</h3>
			</div>
		</div>
	</div>*/
	if ($data[$to])
	{
		if (!$c_status[$to])
		{
	//d($iconwhat);
	//d($data[$to]); 
			if ($data[$to]<10 && $iconwhat != "good.png")
			{
	
				if ($town[12]+$town[3]+$upk[$data[$to]]>$lim[3] && $to != 8)
				{// house kene bypass housing limit
						$upgrade .= boxform("house.png", $lang['upgrade']." ".$buildings[$to][2], '<span class="label label-default">We need more housing, already at full employment.</span>',$co.showlevel($data[$to]), $lang['noHouses']);
				}
				else if (!(($res[0]>=$cost[0]*pow($r, $data[$to]))&&($res[1]>=$cost[1]*pow($r, $data[$to]))&&($res[2]>=$cost[2]*pow($r, $data[$to]))&&($res[3]>=$cost[3]*pow($r, $data[$to]))&&($res[4]>=$cost[4]*pow($r, $data[$to]))))
				{
					$upgrade .= boxform("nores.png", $lang['upgrade']." ".$buildings[$to][2], '<span class="label label-danger">Unable to upgrade because lack of resources.</span>',$co, $lang['noResources'], showlevel($data[$to]));
				}
				else
				{
					$lvl=showlevel($data[$to]);
					$lnk = "<a class='btn btn-success btn-block' href='build.php?town=".$town[0]."&b=".$buildings[$to][0]."&subB=-1'>".$lang['upgrade']." ".$buildings[$to][2]." ".$lang['toLevel']." ".($data[$to]+1)."</a>";
					$upgrade .= boxform("upgrade.png", $lang['upgrade']." ".$buildings[$to][2], '<span class="label label-primary">Upgrade this building ?</span>',$co, $lnk, $lvl, "building");
				}
			}
			else
			{
				$lvl=showlevel($data[$to]);
				$upgrade .= boxform("finish.png", 
				$lang['buildingMaxLvl'],
				'<span class="label label-success">Building is already at maximum level</span>', 
				'<span class="label label-success  center-block">'.$lang["buildingMaxLvl"].'</span><img class="thumbnail center-block" src="'.$imgpath.'finish.png">',
				"",
				$lvl,
				"building");
			}
		}
		else
		{
			$lvl=showlevel($data[$to]);
			$upgrade .= boxform("construct.png", 
			$lang['upgrade']." ".$buildings[$to][2], 
			$co, 
			$lang['beingUpgraded'],
			'<span class="label label-warning">Please wait until the upgrade complete', 
			$lvl,
			"building");
		}
	}
	else
	{
		$lvl=showlevel($data[$to]);
		$upgrade .= boxform("land.png", 
		$lang['constrBuilding'], 
		$co,
		'<span class="label label-danger">Requirement must be fufilled first</span>', 
		'<a class="btn btn-danger btn-block" href="hall.php?town='.$town[0].'">Complete the requirement in town hall.</a>', 
		$lvl,
		"building");
	}
return $upgrade;
}
function BlankHeader($town, $lim, $title, $desc,$icon)
{
$output = '<div id="nodehead" class="row clearfix">
	<div class="col-md-12 column">
		<div class="page-header">
			<h1>'.$title.'<small>'.$desc.'</small></h1>
		</div>
	</div>
</div>
<div id="nodemedia" class="row clearfix">
	<div class="col-md-2 column">
		<div class="thumbnail">
			<img  alt="140x140" src="default/1/'.$icon.'">
			<div class="caption">
				<h3>'.$title.'</h3>
			</div>
		</div>
	</div>
	<div class="col-md-10 column">
	<div class="row clearfix">';
		if($lim)
		{$output .= '<div class="col-md-12 column">'.showproduction($town,$lim).'</div>';}
$output .= '
	</div>
<ul class="nav nav-tabs nav-justified">
	<li class="active"><a href="#">Construction</a></li>
	<li><a href="#">Building</a></li>
	<li><a href="#">Tasks</a></li>
	<li><a href="#">Inventory</a></li>
</ul>
		
<div class="col-md-12 column well well-sm"><img class="center-block" src="http://127.0.0.1/ads_unit/I728x90_Leaderboard.png"/></div>
	</div>
</div>';
return $output;
}
function CardBuilding( $icon,$title,$msg,$extra="", $cost="")
{
	global $lang;
	$output = "";
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	$details = '<div class="media">
  <a class="pull-left" href="#">
    <img class="media-object thumbnail" src="'.$imgpath.$icon.'" alt="'.$title.'">
  </a>
  <div class="media-body">
    <h4 class="media-heading">'.$title.'</h4>
    '.$msg.'
  </div>
</div>
';
	$costandattribute = '
	<div class="row clearfix">
		<div class="col-md-8 column">
		'.$cost.'
		</div>
		<div class="col-md-4 column">
		'.$extra.'
		</div>
	</div>';
	$output .= PageSection("troopform", 12, $title, $details.$costandattribute, "form","panel-danger");
	//$output = PageSection("troopform", 12, $title, $card, "form","panel-danger");
	return $output;
}
function PageSection($id, $col=12,$title='', $body='', $footer='', $context='panel-default',$table = "")
{
/*
<div class="container">
	<div class="row clearfix">
		<div id="'.$id.'" class="col-md-'.$col.' column">
		</div>
	</div>
</div>
*/
$output = '
<div id="'.$id.'" class="row clearfix">
	<div class="col-md-'.$col.' column">
		<div class="panel '.$context.'">';
	if($title != '')		
	{	
		$output .= '
			<div class="panel-heading"><h3 class="panel-title">'.$title.'</h3></div>';	}
	$output .= '
			<div class="panel-body">
				'.$body . ads(0,"pagesection").'
				<a href="#top"><button type="button" class="btn btn-primary btn-xs pull-right">Back to top</button></a>
			</div>
			<div class="panel-footer">'.$footer.'</div>
		</div>
	</div>
</div>';
return $output;
}
function buildingproduction()
{
	return PageSection("bp", 12 ,"Production","Body","");
}
function buildingheader($to,$buildings,$data,$lim,$town,$extra="")
{
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
$output = '
<div id="nodehead" class="row clearfix">
	<div class="col-md-12 column">
		<div class="jumbotron">
			<p>'.$buildings[$to][2].' <small>'.$buildings[$to][8].'</small></p>
		</div>
	</div>
</div>
<div id="nodemedia" class="row clearfix">
	<div class="col-md-12 column">';
$output .= showproduction($town,$lim);
$output .= '
<ul class="nav nav-tabs nav-justified">
	<li class="active"><a href="#">Construct/Produce</a></li>
	<li><a href="#">Upgrade Building</a></li>
	<li><a href="#">Tasks Queue</a></li>
	<li><a href="#">Items Inventory</a></li>
</ul>
		'.ads(1,"header").'
	</div>
</div>';
return $output;
}
function buildingsub($town, $buildings, $to, $restype, $lim, $c_status)
{
	global $lang;
	$output = "";
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}

	$imgpath = $imgs.$fimgs;
	$r=$faction[3];

	$data=explode("-", $town[8]);
	$res=explode("-", $town[10]);
	$prod=explode("-", $town[9]);

	$land=explode("/", $town[13]);
	$land=explode("-", $land[$to]);
	//$output .= "<pre>".print_r($land)."</pre>";
	$toicon = "b".$to.".png";
	//d($c_status);
	
	
		$all_land_upgrade_status = "";
	//status tanah farm
	if (!$c_status[$to])
	{
		for ($i=0; $i<count($land); $i++)
		{
			$all_land_upgrade_status .= $i."<br>";
			if ($land[$i]<10)
			{

				//echo buildingsub($land,$buildings,$to,$i,$c_status);
				$name=explode("-", $buildings[$to][2]);
				$dur=explode("-", $buildings[$to][6]);
				$upk=explode("-", $buildings[$to][7]);
				$cost=explode("-", $buildings[$to][4]);
				$out=explode("-", $buildings[$to][5]);
				$dur[$land[$i]]=explode(":", $dur[$land[$i]]);
				//$tag=$i."pppp<a class='q_link' href='build.php?town=".$town[$to]."&b=".$buildings[$to][0]."&subB=".$i."'>".$lang['upgrade']." ".$name[1]." ".$i." ".$lang['toLevel']." ".($land[$i]+1)."</a>";
				//$tag=$tag."</br>".$lang['cost'].": <img src='".$imgs.$fimgs."00.gif' title='".$lang['crop']."'>".floor($cost[0]*pow($r, $land[$i]))." <img src='".$imgs.$fimgs."01.gif' title='".$lang['lumber']."'>".floor($cost[1]*pow($r, $land[$i]))." <img src='".$imgs.$fimgs."02.gif' title='".$lang['stone']."'>".floor($cost[2]*pow($r, $land[$i]))." <img src='".$imgs.$fimgs."03.gif' title='".$lang['iron']."'>".floor($cost[3]*pow($r, $land[$i]))." <img src='".$imgs.$fimgs."04.gif' title='".$lang['gold']."'>".floor($cost[4]*pow($r, $land[$i]))."</br>".$lang['duration'].": ".($dur[$land[$i]][0]*$lim[$restype]/100).":".($dur[$land[$i]][1]*$lim[$restype]/100)."</br>".$lang['upkeep'].": ".$upk[$land[$i]]."</br>".$lang['expProduction'].": ".$out[$land[$i]];

				$co = cost(
				floor($cost[0]*pow($r, $land[$i])),
				floor($cost[1]*pow($r, $land[$i])),
				floor($cost[2]*pow($r, $land[$i])),
				floor($cost[3]*pow($r, $land[$i])),
				floor($cost[4]*pow($r, $land[$i])),
				($dur[$land[$i]][0]*$lim[$restype]/100).":".($dur[$land[$i]][1]*$lim[$restype]/100),
				"upk.png",$lang['upkeep'],$upk[$land[$i]],
				"factory.png",$lang['expProduction'],$out[$land[$i]]);
				$tag="<a class='q_linkok' href='build.php?town=".$town[0]."&b=".$buildings[$to][0]."&subB=".$i."'>".$lang['upgrade']." ".$name[1]." ".$i." ".$lang['toLevel']." ".($land[$i]+1)."</a>";
				$all_land_upgrade_status .= "<br>".box("upgrade.png", $lang['upgrade']." ".$name[1]." ".$i, $co.showlevel($land[$i])."<br>".$tag);

				//echo $tag;
				if ($town[12]+$town[3]+$upk[$land[$i]]>$lim[3])
				{
					$all_land_upgrade_status .= box("house.png", $lang['upgrade']." ".$name[1]." ".$i, $co.showlevel($land[$i])."<br>".$lang['noHouses'],$co);
					//	label("</br>".$lang['noHouses']);
				}
				if (!(($res[0]>=$cost[0]*pow($r, $land[$i]))&&($res[1]>=$cost[1]*pow($r, $land[$i]))&&($res[2]>=$cost[2]*pow($r, $land[$i]))&&($res[3]>=$cost[3]*pow($r, $land[$i]))&&($res[4]>=$cost[4]*pow($r, $land[$i]))))
				{
					$all_land_upgrade_status .= box("nores.png", $lang['upgrade']." ".$name[1]." ".$i, $co.showlevel($land[$i])."<br>".$lang['noResources'],$co);
					//	label("</br>".$lang['noResources']);
				}
				//echo "</br>--------func----------------------------------</br>";
			}
			else
			{
				//echo $lang['buildingMaxLvl']."</br></br>";
				$bo=showlevel($land[$i])."<br>";

				$all_land_upgrade_status .= box("finish.png", $lang['buildingMaxLvl']." ".$name[1], $co.$bo);
			}

		}// for each land
	}
	else
	{
		$all_land_upgrade_status  .= box("construct.png", $lang['upgrade']." ".$name[1], $co.$lang['beingUpgraded'],$co);
		//echo "</br></br></br></br></br></br>".$lang['beingUpgraded']."</br></br></br></br></br></br></br></br>";
	}
	//$output .= buildingheader($to,$buildings,$all_land_upgrade_status);
	$output .= $all_land_upgrade_status;
	/*
		else
		{
		echo "</br></br></br></br></br></br>".$lang['constrBuilding']."</br></br></br></br></br></br></br></br>";
		}
		*/

/*	dah tak guna sebab ada buildingstandard
if (!$c_status[$to])
	{
		if ($land[$i]<10)
			{
			$dur=explode("-", $buildings[$to][6]);
			$upk=explode("-", $buildings[$to][7]);
			$cost=explode("-", $buildings[$to][4]);
			$dur[$land[$i]]=explode(":", $dur[$land[$i]]);
			$out=explode("-",$buildings[$to][5]);

			$co = cost(
			floor($cost[0]*pow($r, $land[$i])),
			floor($cost[1]*pow($r, $land[$i])),
			floor($cost[2]*pow($r, $land[$i])),
			floor($cost[3]*pow($r, $land[$i])),
			floor($cost[4]*pow($r, $land[$i])),
			($dur[$land[$i]][0]*$lim[4]/100).":".($dur[$land[$i]][1]*$lim[4]/100),
			"upk.png",$lang['upkeep'],$upk[$land[$i]],
			$iconwhat,$givewhat,$out[$land[$i]]);
			if ($town[12]+$town[3]+$upk[$land[$i]]>$lim[3])
				{
				$upgrade .= box("house.png", $lang['upgrade']." ".$buildings[$to][2], $co.showlevel($land[$i])."<br>".$lang['noHouses']);
				}
			else if (!(($res[0]>=$cost[0]*pow($r, $land[$i]))&&($res[1]>=$cost[1]*pow($r, $land[$i]))&&($res[2]>=$cost[2]*pow($r, $land[$i]))&&($res[3]>=$cost[3]*pow($r, $land[$i]))&&($res[4]>=$cost[4]*pow($r, $land[$i]))))
				{
				$upgrade .= box("nores.png", $lang['upgrade']." ".$buildings[$to][2], $co.showlevel($data[$to])."<br>".$lang['noResources']);
				}
			else
				{
				$bo=showlevel($land[$i])."<br><a class='q_linkok' href='build.php?town=".$town[0]."&b=".$buildings[$to][0]."&subB=".$i."'>".$lang['upgrade']." ".$buildings[$to][2]." ".$lang['toLevel']." ".($land[$i]+1)."</a>";
				$upgrade .= boxform("upgrade.png", $lang['upgrade']." ".$buildings[$to][2], $co, $bo);
			//boxform($icon,$title,$text,$cost,$form,$extra="")
				}
			}
		else
			{
			$upgrade .= boxform("finish.png", $lang['buildingMaxLvl'], .$lang['buildingMaxLvl'], $co,$lang['buildingMaxLvl']);
			}
	}
else
	{
	$upgrade .= box("construct.png", $lang['upgrade']." ".$buildings[$to][2], $co.$lang['beingUpgraded']);
	}
	dah tak guna sebab ada buildingstandard
*/
	
	return $output;
}

function box( $icon,$title,$msg,$extra="", $cost="")
{
	global $lang;
	$output = "";
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	$output .= "\n<table class='table'><tr>";
	$output .= "<td colspan='3' width='80%' ><h2>".$title."</h2><hr></td>";
	$output .= "</tr><tr>";
	$output .= "<td rowspan='2' width='10%'><center><img src='".$imgpath.$icon."' align='absmiddle' title='".$title."'></center></td>";
	$output .= "<td>ww".$msg."</td>";
	//$output .= "</tr><tr>";
	if ($extra)
	{
		//$output .= "</tr><tr>";
		$output .= "<td>".$extra."</td>";
		//$output .= "</tr><tr>";
	}
	$output .= "</tr></table>";
	$details = '<div class="media">
  <a class="pull-left" href="#">
    <img class="media-object thumbnail" src="'.$imgpath.$icon.'" alt="'.$title.'">
  </a>
  <div class="media-body">
    <h4 class="media-heading">'.$title.'</h4>
    '.$msg.'
  </div>
</div>
';
	$costandattribute = '
	<div class="row clearfix">
		<div class="col-md-8 column">
		'.$cost.'
		</div>
		<div class="col-md-4 column">
		'.$extra.'
		</div>
	</div>';
	$output .= PageSection("troopform", 12, $title, $details.$costandattribute, "form","panel-danger");
	return $output;
}

function boxform($icon,$title,$text,$cost,$form,$extra="", $id="media")
{
	global $lang;
	$output = "";
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
//PageSection($id, $col=12,$title='', $body='', $footer='', $context='panel-default',$table = "")
$details = '
<div class="media"><a class="pull-left" href="#"><img class="media-object thumbnail" src="'.$imgpath.$icon.'" alt="'.$title.'"></a>
	<div class="media-body">
		<h4 class="media-heading">'.$title.'</h4>
		'.$text.'
	</div>
</div>';
$costandattribute = '
<div class="row clearfix">
	<div class="col-md-6 column">'.ads(1,"building").'
	</div>
	<div class="col-md-6 column">'.$extra.$cost.'
	</div>
</div>';
	$output .= PageSection($id, 12, $title, $details.$costandattribute, $form);
	return $output;
}
function showtrooptrainingform($afifio)
{
	$lang = $afifio["lang"];
	$units = $afifio["units"];
	
	$w_upgrades = $afifio["w_upgrades"];
	$u_upgrades = $afifio["u_upgrades"];
	$a_upgrades = $afifio["a_upgrades"];
	$s_upgrades = $afifio["s_upgrades"];
	$lim = $afifio["lim"];
			for ($i=11; $i<=11; $i++)
			{
				$dur=explode(":", $units[$i][9]);
				$cost=explode("-", $units[$i][4]);
/*				if (($u_upgrades[$i])&&($w_upgrades[$i])&&($a_upgrades[$i])) echo "<form name='units' method='post' action='train.php?town=".$_GET["town"]."&type=".$i."'><tr style='text-align: center;'><td><img src='".$imgs.$fimgs."2".$i.".gif' title='".$units[$i][2]."'></br>".$units[$i][10]."</br>".$lang['cost'].": <img src='".$imgs.$fimgs."00.gif' title='".$lang['crop']."'>".floor($cost[0])." <img src='".$imgs.$fimgs."01.gif' title='".$lang['lumber']."'>".floor($cost[1])." <img src='".$imgs.$fimgs."02.gif' title='".$lang['stone']."'>".floor($cost[2])." <img src='".$imgs.$fimgs."03.gif' title='".$lang['iron']."'>".floor($cost[3])." <img src='".$imgs.$fimgs."04.gif' title='".$lang['gold']."'>".floor($cost[4])."</br>".$lang['duration'].": ".($dur[0]*$lim[8]/100).":".($dur[1]*$lim[8]/100).", HP: ".($units[$i][5]+$u_upgrades[$i]).", ".$lang['atk'].": ".($units[$i][6]+$w_upgrades[$i]).", ".$lang['def'].": ".($units[$i][7]+$a_upgrades[$i]).", ".$lang['speed'].": ".$units[$i][8].".</td><td><input class='textbox' name='q' type='text' size='3' maxlength='3' value='0'></td><td><input type='submit' class='button' name='unit' value='".$lang['train']."'></td></tr></form>";
				else echo "<tr style='text-align: center;'><td><img src='".$imgs.$fimgs."2".$i.".gif' title='".$units[$i][2]."'></br>".$units[$i][10]."</td><td colspan='2'>".$lang['researchUnit']." ".$lang['in']." ";
				if (!$u_upgrades[$i]) echo $buildings[16][2]."</td></tr>";
				else if (!$w_upgrades[$i]) echo $buildings[17][2]."</td></tr>";
				else if (!$a_upgrades[$i]) echo $buildings[17][2]."</td></tr>";
*/

			$form = '
<div class="row clearfix">
	<form role="form" name="units" method="post" action="train.php?town='.$_GET["town"].'&type='.$i.'">
		<div class="col-md-6 column"><input class="form-control" name="q" type="text" size="7" maxlength="7" value="1"></div>
		<div class="col-md-6 column"><input type="submit" class="btn btn-block btn-success" name="unit" value="'.$lang["train"].'"></div>
	</form>
</div>';
				$co = cost(floor($cost[0]),
						floor($cost[1]),
						floor($cost[2]),
						floor($cost[3]),
						floor($cost[4]),
						($dur[0]*$lim[8]/100).":".($dur[1]*$lim[8]/100),
		"hp.png",   $lang['hp'],  ($units[$i][5]+$u_upgrades[$i])."</b> [".$units[$i][5]."+".$u_upgrades[$i]."]",
		"atk.png",  $lang['atk'],  ($units[$i][6]+$w_upgrades[$i])."</b> [".$units[$i][6]."+".$w_upgrades[$i]."]",
		"def.png",  $lang['def'],  ($units[$i][7]+$a_upgrades[$i])."</b> [".$units[$i][7]."+".$a_upgrades[$i]."]",
		"spd.png", $lang['spd'],  $units[$i][8], "",
		"", "", "",
		"", "", "");
						$attr = unitattribute($units[$i],$u_upgrades[$i],$w_upgrades[$i],$a_upgrades[$i],$s_upgrades[$i]);
				return boxform("2".$i.".gif", $units[$i][2], $units[$i][10], $co, $form,$attr);
			} 
}
function tdlink($link,$text,$level = "")
{
	global $lang;
	$output = "";
	$output .= "<br>".img("lvl".$level.".png",$lang['level']." ".$level)." <a class='q_linkok' href='".$link."'>".$text."</a>";
	return $output;
}

function showarmylist($town,$units,$army)
{
	global $lang;
	
	$output = "\n";
	$output .= '<table class="table table-condensed table-hover table-striped"><thead>';
				
	$output .= '<tr><th colspan="'.count($units).'">'.$lang['currentStorCap'].'</th>';
	$output .= "</tr></thead>";
	$output .= "<tbody><tr>";
	for ($i=0; $i<count($units); $i++)
	{
		$output .= "\n<td>".img("2".$i.".gif",$units[$i][2])."</td>";
	}
	$output .= "</tr><tr>";
	for ($i=0; $i<count($army); $i++)
	{
		$output .= "\n";
		$output .= '<td><span class="label label-default">'.$army[$i].'</span></td>';
	}
	$output .= "</tr><tbody>
			</table>";



	/*	<div class="list-group">
  <a href="#" class="list-group-item active">
    <h4 class="list-group-item-heading">List group item heading</h4>
    <p class="list-group-item-text">...</p>
  </a>
</div>
* $output .= "<tr><td colspan='".count($units)."'>";
	 $output .= img("link.png","Links")."<a class='q_linkok' href='academy.php?town=".$town[0]."'>Research</a> | ";
	 $output .= "<a class='q_linkok' href='go.php?to=17&town=".$town[0]."'>Upgrades</a> | ";
	 $output .= "<a class='q_linkok' href='house.php?town=".$town[0]."'>Housing</a> | ";
	 $output .= "<a class='q_linkok' href='barracks.php?town=".$town[0]."'>Train</a> | ";
	 $output .= "<a class='q_linkok' href='washop.php?to=18&town=".$town[0]."'>Equipment</a> | ";
	 $output .= "<a class='q_linkok' href='wwarehouse.php?town=".$town[0]."'>Storage</a> | ";
	 $output .= "<a class='q_linkok' href='stable.php?town=".$town[0]."'>Horses</a> | ";
	 $output .= "<a class='q_linkok' href='port.php?town=".$town[0]."'>Ships</a> | ";
	 $output .= "<a class='q_linkok' href='sshop.php?town=".$town[0]."'>Siege</a> | ";
	 $output .= "<a class='q_linkok' href='dispatch.php?town=".$town[0]."'>Command</a> | ";Your total military capabilities
	 $output .= "</td>";*/
	 
	$footer = "";
	 $footer .= img("link.png","Links");
	 $footer .= "<a class='q_linkok' href='dispatch.php?town=".$town[0]."'>Command</a> | ";
	 $footer .= "<a class='q_linkok' href='house.php?town=".$town[0]."'>Housing</a> | ";
	 $footer .= "<a class='q_linkok' href='barracks.php?town=".$town[0]."'>Barracks</a> | ";
	 $footer .= "<a class='q_linkok' href='stable.php?town=".$town[0]."'>Stables</a>|";
	 $footer .= "<a class='q_linkok' href='port.php?town=".$town[0]."'>Port</a> | ";
	 $footer .= "<a class='q_linkok' href='sshop.php?town=".$town[0]."'>Siege Workshop</a> | ";
	return PageSection("trooplist",12,$lang["availableTroops"], $output, $footer.'  ');
}

function showweaponlist($town,$lim,$weapons,$weaps)
{
	global $lang;
	$blacksmithproduct = array(0,1,2);
	$armoursmithproduct = array(5,6,7,8);
	$workshopproduct = array(3,4,10);
	$stableproduct = array(9);
	$output = '<table class="table table-condensed table-hover table-striped"><thead>';
				
	$output .= '<tr><th colspan="'.count($weapons).'">'.$lang['currentStorCap']." ".$lim[12]."</th>";
	$output .= "</tr></thead>";
	$output .= "<tbody><tr>";
	for ($i=0; $i<count($weapons); $i++)
	{
		$link = "";
		if (findin($weapons[$i][0],$blacksmithproduct))
		{
			$link = "go.php?town=".$town[0];
		}
		else if (findin($weapons[$i][0],$armoursmithproduct))
		{
			$link = "washop.php?town=".$town[0];
		}
		else if (findin($weapons[$i][0],$workshopproduct))
		{
			$link = "sshop.php?town=".$town[0];
		}
		else if (findin($weapons[$i][0],$stableproduct))
		{
			$link = "stable.php?town=".$town[0];
		}
		else
		{
			$link = "#";
		}
		$output .= '<td><a href="'.$link.'">'.img("1".$i.".gif",$weapons[$i][2]).'</a></td>';

	}
	$output .= "</tr><tr>";
	if ($weaps)
	{
		for ($i=0; $i<count($weaps); $i++)
		{
			$output .= '<td>'.LabelColor($weaps[$i], $lim[12],1).'</td>';
		}
	}
$output .= "</tr></table>";

	$footer = "";
	 $footer .= img("link.png","Links");
	 $footer .= "<a class='q_linkok' href='washop.php?to=18&town=".$town[0]."'>Armoursmith</a> | ";
	 $footer .= "<a class='q_linkok' href='go.php?town=".$town[0]."'>Blacksmith</a> | ";
	 $footer .= "<a class='q_linkok' href='wwarehouse.php?town=".$town[0]."'>Weapon Warehouse</a>";
	
	return PageSection("weaponlist",12,$lang['weapStock'],$output,$footer);
}

function LabelProdColor($id, $current, $limit=1, $showprogress=0)
{
	if(!$limit) {$current = 0;$limit = 1;}
	$percent=($current/$limit)*100;
	$result = "default";
	if($percent <= 10)
	{
		$result = "danger";
	}
	if($percent > 10 && $percent <= 39 )
	{
		$result = "info";
	}
	if($percent >= 40 && $percent <= 59 )
	{
		$result = "success";
	}
	if($percent >= 60 && $percent <= 79 )
	{
		$result = "primary";
	}
	if($percent >= 80 && $percent <= 99 )
	{
		$result = "warning";
	}
	if($percent >= 100)
	{
		$result = "danger";
	}
	$bar = "";
	if($showprogress)
	{
		$bar = '<br>
		<div class="progress progress-striped">
			<div class="progress-bar progress-bar-'.$result.'" role="progressbar" aria-valuenow="'.$percent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$percent.'%">
				<span class="sr-only">'.$percent.'%</span>
			</div>
		</div>';
	}
	return '<span class="label label-'.$result.'"><span id="'.$id.'">0000</span>/'.$limit.'</span>'.$bar;
}
function LabelColor($current=1, $limit=1, $showprogress=0)
{

	if(!$limit) {$current = 0;$limit = 1;}
	$percent=($current/$limit)*100;
	$result = "default";
	if($percent <= 10)
	{
		$result = "danger";
	}
	if($percent > 10 && $percent <= 39 )
	{
		$result = "info";
	}
	if($percent >= 40 && $percent <= 59 )
	{
		$result = "success";
	}
	if($percent >= 60 && $percent <= 79 )
	{
		$result = "primary";
	}
	if($percent >= 80 && $percent <= 99 )
	{
		$result = "warning";
	}
	if($percent >= 100)
	{
		$result = "danger";
	}
	$bar = "";
	if($showprogress)
	{
		$bar = '<br>
		<div class="progress">
			<div class="progress-bar progress-bar-'.$result.'" role="progressbar" aria-valuenow="'.$percent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$percent.'%">
				<span class="sr-only">'.$percent.'%</span>
			</div>
		</div>';
	}
	return '<span class="label label-'.$result.'">'.$current.'/'.$limit.'</span>'.$bar;
}

function buildingcost($crop,$lumber,$stone,$iron,$gold,$duration
,$extra1icon = "",$extra1text = "",$extra1 = ""
,$extra2icon = "",$extra2text = "",$extra2 = ""
,$extra3icon = "",$extra3text = "",$extra3 = ""
,$extra4icon = "",$extra4text = "",$extra4 = ""
,$extra5icon = "",$extra5text = "",$extra5 = ""
,$extra6icon = "",$extra6text = "",$extra6 = ""
,$actionbars = "")
{
	global $lang;

	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
		$output = '
<table class="table table-bordered">
	<thead>
		<tr>
			<th colspan="3" class="active">Cost</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>'.img("r00.png",$lang['crop']).' '.$lang['crop'].'<span class="label label-default pull-right">'.$crop.'</span></td>
			<td>'.img("r01.png",$lang['lumber']).' '.$lang['lumber'].'<span class="label label-default pull-right">'.$lumber.'</span></td>
			<td>'.img("r02.png",$lang['stone']).' '.$lang['stone'].'<span class="label label-default pull-right">'.$stone.'</span></td>
		</tr>
		<tr>
			<td>'.img("r03.png",$lang['iron']).' '.$lang['iron'].'<span class="label label-default pull-right"> '.$iron.' </span></td>
			<td>'.img("r04.png",$lang['gold']).' '.$lang['gold'].'<span class="label label-default pull-right">'.$gold.'</span></td>
			<td>'.img("r06.png",$lang['duration']).' <span class="label label-warning">'.$lang['duration'].'</span><span class="label label-default pull-right">'.$duration.'</span></td>
		</tr>';
	if ($extra1text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra1icon,$extra1text).' '.$extra1text.": <b class='b'>".$extra1.'</b></td></tr>';
	}
	if ($extra2text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra2icon,$extra2text).' '.$extra2text.": <b class='b'>".$extra2.'</b></td></tr>';
	}
	if ($extra3text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra3icon,$extra3text).' '.$extra3text.": <b class='b'>".$extra3.'</b></td></tr>';
	}
	if ($extra4text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra4icon,$extra4text).' '.$extra4text.": <b class='b'>".$extra4.'</b></td></tr>';
	}
	if ($extra5text)
	{
		$output .= '<tr><td colspan="3">'.img($extra5icon,$extra5text).' '.$extra5text.": <b class='b'>".$extra5.'</b></td></tr>';
	}
	if ($extra6text)
	{
		$output .= '<tr><td colspan="3">'.img($extra6icon,$extra6text)." ".$extra6text.": <b class='b'>".$extra6.'</b></td></tr>';
	}
	$output .= '
		</tbody>
</table>';
	return $output;
}
function cost($crop,$lumber,$stone,$iron,$gold,$duration
,$extra1icon = "",$extra1text = "",$extra1 = ""
,$extra2icon = "",$extra2text = "",$extra2 = ""
,$extra3icon = "",$extra3text = "",$extra3 = ""
,$extra4icon = "",$extra4text = "",$extra4 = ""
,$extra5icon = "",$extra5text = "",$extra5 = ""
,$extra6icon = "",$extra6text = "",$extra6 = ""
,$actionbars = "")
{
	global $lang;

	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
		$output = '
<table class="table table-bordered">
	<thead>
		<tr>
			<th colspan="2" class="active">Cost</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>'.img("r00.png",$lang['crop']).' '.$lang['crop'].'<span class="label label-default pull-right">'.$crop.'</span></td>
			<td>'.img("r01.png",$lang['lumber']).' '.$lang['lumber'].'<span class="label label-default pull-right">'.$lumber.'</span></td>
		</tr>
		<tr>
			<td>'.img("r02.png",$lang['stone']).' '.$lang['stone'].'<span class="label label-default pull-right">'.$stone.'</span></td>
			<td>'.img("r03.png",$lang['iron']).' '.$lang['iron'].'<span class="label label-default pull-right"> '.$iron.' </span></td>
		</tr>
		<tr>
			<td>'.img("r04.png",$lang['gold']).' '.$lang['gold'].'<span class="label label-default pull-right">'.$gold.'</span></td>
			<td>'.img("r06.png",$lang['duration']).' <span class="label label-warning">'.$lang['duration'].'</span><span class="label label-default pull-right">'.$duration.'</span></td>
		</tr>';
	if ($extra1text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra1icon,$extra1text).' '.$extra1text.": <b class='b'>".$extra1.'</b></td></tr>';
	}
	if ($extra2text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra2icon,$extra2text).' '.$extra2text.": <b class='b'>".$extra2.'</b></td></tr>';
	}
	if ($extra3text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra3icon,$extra3text).' '.$extra3text.": <b class='b'>".$extra3.'</b></td></tr>';
	}
	if ($extra4text)
	{
		$output .= '<tr><td colspan="3" class="active">'.img($extra4icon,$extra4text).' '.$extra4text.": <b class='b'>".$extra4.'</b></td></tr>';
	}
	if ($extra5text)
	{
		$output .= '<tr><td colspan="3">'.img($extra5icon,$extra5text).' '.$extra5text.": <b class='b'>".$extra5.'</b></td></tr>';
	}
	if ($extra6text)
	{
		$output .= '<tr><td colspan="3">'.img($extra6icon,$extra6text)." ".$extra6text.": <b class='b'>".$extra6.'</b></td></tr>';
	}
	$output .= '
		</tbody>
</table>';
	return $output;
}
function costinfo($lim,$cost,$dur,$req)
{
	global $lang;
	$crop = floor($cost[0]);
	$lumber = floor($cost[1]);
	$stone = floor($cost[2]);
	$iron = floor($cost[3]);
	$gold = floor($cost[4]);
	($dur[0]*$lim[8]/100).":".($dur[1]*$lim[8]/100);
	$output = "\n<table class='cost' border='1'><tr>";
	$output .= "<td>opopopop".img("r00.png",$lang['crop'])."</td>";
	$output .= "<td><img src='".$imgpath."r01.png' align='absmiddle' title='".$lang['lumber']."'> ".$lumber."</td>";
	$output .= "<td><img src='".$imgpath."r02.png' align='absmiddle' title='".$lang['stone']."'> ".$stone."</td>";
	$output .= "<td><img src='".$imgpath."r03.png' align='absmiddle' title='".$lang['iron']."'> ".$iron."</td>";
	$output .= "<td><img src='".$imgpath."r04.png' align='absmiddle' title='".$lang['gold']."'> ".$gold."</td>";
	$output .= "<td><img src='".$imgpath."r06.png' align='absmiddle' title='".$lang['duration']."'> ".$duration."</td>";

	$output .= "</tr><tr><td colspan='6'>";
	if ($extra1text)
	{
		$output .= img($extra1icon,$extra1text)." ".$extra1text.": <b class='b'>".$extra1."</b> ";
	}
	if ($extra2text)
	{
		$output .= img($extra2icon,$extra2text)." ".$extra2text.": <b class='b'>".$extra2."</b> ";
	}
	if ($extra3text)
	{
		$output .= img($extra3icon,$extra3text)." ".$extra3text.": <b class='b'>".$extra3."</b> ";
	}
	if ($extra4text)
	{
		$output .= img($extra4icon,$extra4text)." ".$extra4text.": <b class='b'>".$extra4."</b> ";
	}
	if ($extra5text)
	{
		$output .= img($extra5icon,$extra5text)." ".$extra5text.": <b class='b'>".$extra5."</b> ";
	}
	if ($extra6text)
	{
		$output .= img($extra6icon,$extra6text)." ".$extra6text.": <b class='b'>".$extra6."</b> ";
	}
	$output .= "</td></tr></table>";
	return $output;
}
function unitattribute($units,$u_upgrades,$w_upgrades,$a_upgrades,$s_upgrades,$type="2")
{
	global $lang;
	$output = "\n<table class='table well well-sm' ><tr>";
	$output .= "<td>Attributes</td>";
	$output .= "<td>".img("hp.png", $lang['hp'])."</td>";
	$output .= "<td>".img("atk.png", $lang['atk'])."</td>";
	$output .= "<td>".img("def.png", $lang['def'])."</td>";
	$output .= "<td>".img("spd.png", $lang['spd'])."</td>";
	$output .= "</tr><tr>";
	$output .= "<td>Basic</td>";
	$output .= "<td class='a'>".$units[5]."</td>";
	$output .= "<td class='a'>".$units[6]."</td>";
	$output .= "<td class='a'>".$units[7]."</td>";
	$output .= "<td class='a'>".$units[8]."</td>";
	$output .= "</tr><tr>";
	$output .= "<td>Academy</td>";
	$output .= "<td class='b'>+".$u_upgrades."</td>";
	$output .= "<td class='b'>+".$w_upgrades."</td>";
	$output .= "<td class='b'>+".$a_upgrades."</td>";
	$output .= "<td class='b'>+".$s_upgrades."</td>";
	$output .= "</tr><tr>";
	$output .= "<td>Total</td>";
	$output .= "<td class='a'>".($u_upgrades+$units[5])."</td>";
	$output .= "<td class='a'>".($w_upgrades+$units[6])."</td>";
	$output .= "<td class='a'>".($a_upgrades+$units[7])."</td>";
	$output .= "<td class='a'>".($s_upgrades+$units[8])."</td>";
	/*$output .= "</tr><tr>";
	 $output .= "<td>Food</td>";
	 $output .= "<td class='a'>X</td>";
	 $output .= "<td class='a'>X</td>";
	 $output .= "<td class='a'>X</td>";
	 $output .= "<td class='a'>X</td>";*/
	$output .= "</tr></table>";
	return $output;
}
function showcost($imgicon,$title,$crop,$lumber,$stone,$iron,$gold,$duration,$extra = "")
{
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;

	$output = "\n<table class='cost' border='1'><tr>";
	$output .= "<td width='100%' colspan='4'><b><u>".$title."</u></b><hr></td>";
	$output .= "</tr><tr>";
	$output .= "<td rowspan='3'>uhhhhhh<img src='".$imgpath.$imgicon."' align='absmiddle' title='".$title."'></td>";
	$output .= "<td width='33%'><img src='".$imgpath."r00.png' align='absmiddle' title='".$lang['crop']."'> ".$crop."</td>";
	$output .= "<td width='33%'><img src='".$imgpath."r01.png' align='absmiddle' title='".$lang['lumber']."'> ".$lumber."</td>";
	$output .= "<td width='33%'><img src='".$imgpath."r06.png' align='absmiddle' title='".$lang['duration']."'> ".$duration."</td>";
	$output .= "</tr><tr>";
	$output .= "<td width='33%'><img src='".$imgpath."r02.png' align='absmiddle' title='".$lang['stone']."'> ".$stone."</td>";
	$output .= "<td width='33%'><img src='".$imgpath."r03.png' align='absmiddle' title='".$lang['iron']."'> ".$iron."</td>";
	$output .= "<td width='33%'><img src='".$imgpath."r04.png' align='absmiddle' title='".$lang['gold']."'> ".$gold."</td>";
	$output .= "</tr><tr>";
	$output .= "<td  colspan='4'>".$extra."</td>";
	$output .= "</tr><tr>";
	$output .= "</tr></table>";
	return $output;
}
function showcost2($title,$level,$uplink,$crop,$lumber,$stone,$iron,$gold,$plants,$duration,$extra = "")
{
	global $lang;
		if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	$output = "\n<table class='cute'><tr>";
	$output .= "<td width='100%' colspan='4'>pooooooooo<img src='".$imgpath.$title[0]."' align='absmiddle' title='".$title[1]."'> <b><u>".$title[1]."</u></b><hr></td>";
	$output .= "</tr><tr>";
	$output .= "<td width='25%'>".img("r00.png",$lang['crop']).$crop."</td>";
	$output .= "<td width='25%'>".img("r01.png",$lang['lumber']).$lumber."</td>";
	$output .= "<td width='25%'>".img("r06.png",$lang['duration']).$duration."</td>";
	$output .= "</tr><tr>";
	$output .= "<td width='25%'>".img("r02.png",$lang['stone']).$stone."</td>";
	$output .= "<td width='25%'>".img("r03.png",$lang['iron']).$iron."</td>";
	$output .= "<td width='25%'>".img("r04.png",$lang['gold']).$gold."</td>";
	if ($extra != "")
	{
		$output .= "<td width='25%'>".img("plus.png",$extra[1]).$extra[1]." ".$extra[2]."</td>";
	}
	else
	{
		$output .= "<td width='25%'></td>";
	}
	$output .= "</tr><tr>";
	$output .= "<td width='75%' colspan='3'>";
	$output .= showlevel($level);
	$output .= " </td>";
	$output .= "<td width='25%'>".img("tick.png",$lang['upgrade'])." <a class='q_linkok' href='".$uplink."'><b>".$lang['upgrade']."!</b></a></td>";

	$output .= "</tr></table>";
	return $output;
}
function img($img,$imgtext)
{//align='absmiddle' 
	$imgpath = imgpath();
	return "<img src='".$imgpath.$img."' title='".$imgtext."'>";
}
function imgpath()
{
	if (isset($_SESSION["user"][0]))
	{
		$faction=faction($_SESSION["user"][10]);
		$imgs=$_SESSION["user"][13];
		$fimgs=$faction[2];
	}
	else
	{
		$imgs="default/";
		$fimgs="1/";
	}
	$imgs="default/";
	$fimgs="1/";
	return $imgs.$fimgs;
}
function showlevel($level)
{
	global $lang;
	$output = '<table class="table table-bordered well well-sm" >';
	$output .= '<thead><tr><th class="active">'.img("level.png",$lang['level'])." Current level :  ".img("lvl".$level.".png",$lang['level']." ".$level)." <b>".$lang['level']." ".$level."</b></th></tr></thead>";
	$output .= "<tbody><tr><td>";
	for ($o = 1; $o <= $level; $o++ )
	{
	$output .= "\n".img("lvl".$o.".png",$lang['level']." ".$o)." ";
	}
	$output .= "</td></tr>";
	//$output .= "<tr><td>".$text.$building[$to][$level]."</td></tr>";
	$output .= "</tbody></table>";
	return $output;
}
function showcostdisabled($title,$extra = "" )
{
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	$output = "\n<table class='cute'><tr>";
	$output .= "<td width='100%'><img src='".$imgpath.$title[0]."' align='absmiddle' title='".$title[1]."'> <b><u>".$title[1]."</u></b><hr></td>";
	$output .= "</tr><tr>";
	$output .= "<td width='100%'>$extra[2] is being upgraded. You can cancel the process using the queue management.</td>";
	$output .= "</tr><tr>";
	$output .= "</tr></table>";
	return $output;
}
function showres($title,$granary,$warehouse,$bank)
{
	global $lang;
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$output = "\n";
	//$output .= "<img src='".$imgs.$fimgs."00.gif' align='absmiddle' title='".$lang['crop']."'><span id=\"res0\"></span>/".$lim[0]title='".$lang['lumber']."'><span id=\"res1\"></span>/".$lim[1]." <img src='".$imgs.$fimgs."02.gif' title='".$lang['stone']."'><span id=\"res2\"></span>/".$lim[1]." <img src='".$imgs.$fimgs."03.gif' title='".$lang['iron']."'><span id=\"res3\"></span>/".$lim[1]." <img src='".$imgs.$fimgs."04.gif' title='".$lang['gold']."'><span id=\"res4\"></span>/".$lim[2]."</br></br>";

	$output .= " <img src='".$imgs.$fimgs."00.gif' align='absmiddle' title='".$lang['crop']."'> <span id=\"res0\"></span>/".$granary;
	$output .= " <img src='".$imgs.$fimgs."01.gif' align='absmiddle' title='".$lang['lumber']."'> <span id=\"res1\"></span>/".$warehouse;
	$output .= " <img src='".$imgs.$fimgs."02.gif' align='absmiddle' title='".$lang['stone']."'> <span id=\"res2\"></span>/".$warehouse;
	$output .= " <img src='".$imgs.$fimgs."03.gif' align='absmiddle' title='".$lang['iron']."'> <span id=\"res3\"></span>/".$warehouse;
	$output .= " <img src='".$imgs.$fimgs."04.gif' align='absmiddle' title='".$lang['gold']."'> <span id=\"res4\"></span>/".$bank."</br></br>";

	return $output;
}

function showproduction($town,$lim)
{
	global $lang;
	$res=explode("-", $town[10]);
	$prod=explode("-", $town[9]);
	$data=explode("-", $town[8]);
	if ($prod[0]-$town[3]-$town[12]<5)
	{
		$prod[0]=$town[3]+$town[12]+5;//noob protection against negative crop production values
	}
	if (isset($_SESSION["user"][0])) {$faction=faction($_SESSION["user"][10]); $imgs=$_SESSION["user"][13]; $fimgs=$faction[2];}
	else {$imgs=$default_imgs; $fimgs=$default_fimgs;}
	$imgpath = $imgs.$fimgs;
	//$data=explode("-", $town[8]);
	$buildings=buildings($_SESSION["user"][10]);
	$output = '
	<div class="row clearfix">
		<div class="col-md-12 col-sm-6">
			<ul class="nav nav-pills nav-justified">
				<li> '.img("m00.jpg",$lang["crop"]).'<br> '.img("r00.png",$lang['crop']).'<span class="label label-success"> '.($prod[0]-$town[3]-$town[12]).'/h </span><br/>'.LabelProdColor("res0", $res[0],$lim[0],0).'</li>
				<li> '.img("m01.jpg",$lang["lumber"]).'<br/> '.img("r01.png",$lang['lumber']).'<span class="label label-success"> '.$prod[1].'/h </span><br/>'.LabelProdColor("res1", $res[1],$lim[1],0).'</li>
				<li> '.img("m02.jpg",$lang["stone"]).'<br/>'.img("r02.png",$lang['stone']).'<span class="label label-success"> '.$prod[2].'/h </span><br/>'.LabelProdColor("res2", $res[2],$lim[1],0).'</li>
				<li> '.img("m03.jpg",$lang["iron"]).'<br/>'.img("r03.png",$lang['iron']).'<span class="label label-success"> '.$prod[3].'/h </span><br/>'.LabelProdColor("res3", $res[3],$lim[1],0).'</li>
				<li> '.img("m04.jpg",$lang["gold"]).'<br/>'.img("r04.png",$lang['gold']).'<span class="label label-success"> '.$prod[4].'/h </span><br/>'.LabelProdColor("res4", $res[4],$lim[2],0).'</li>
				<li> '.img("m05.jpg",$lang["upkeep"]).'<br/>'.img("upk.png",$lang['upkeep'])." ".LabelColor(($town[3]+$town[12]),$lim[3],0).'<br/> <span class="label label-success">'.$town[5].'%</span></li>
			</ul>
		</div>
	</div>';
/*	dari town.php 	
 * 			<li> '.img("m06.jpg",$lang["Morale"]).'<br/>'.img("morale.png",$lang['Morale']).'</li>
 *            <img src='".$imgs.$fimgs."00.gif' title='".$lang['crop']."'>".($prod[0]-$town[3]-$town[12])."/h 
            <img src='".$imgs.$fimgs."01.gif' title='".$lang['lumber']."'>".$prod[1]."/h 
            <img src='".$imgs.$fimgs."02.gif' title='".$lang['stone']."'>".$prod[2]."/h 
            <img src='".$imgs.$fimgs."03.gif' title='".$lang['iron']."'>".$prod[3]."/h 
            <img src='".$imgs.$fimgs."04.gif' title='".$lang['gold']."'>".$prod[4]."/h</span>";*/


	$output .= "\n<table class='table'><tr>";
	/*if ($data[7]) {$name=explode("-", $buildings[7][2]); if ($data[7]==10) {$i=22; $j=1;} else {$i=7; $j=0;} echo "<area shape='rect' coords='334,105,409,185' style='cursor:url(".$imgs.$fimgs."cursor.png), auto;' href='hall.php?town=".$town[0]."' onmouseout=\"hall.src='".$imgs.$fimgs."b".$i.".png', showtext('-')\" onmouseover=\"hall.src='".$imgs.$fimgs."b".$i."_.png', showtext('".$name[$j]." ".$lang['level']." ".$data[7]."')\">";}

	*/
	/*
	 $output .= "<td width='20%'>".img("item003.jpg",$lang['Morale'])."".img("level.png",$lang['level'])."Resources</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Storage</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Army</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Support And Research</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Infrastructure</td>";
	 
	$output .= '<tr>
	<td> '.img("m00.jpg",$lang["crop"]).'<br> '.img("r00.png",$lang['crop']).'<span class="label label-success"> '.($prod[0]-$town[3]-$town[12]).'/h </span><br/>'.LabelProdColor("res0", $res[0],$lim[0],0).'</td>
	<td> '.img("m01.jpg",$lang["lumber"]).'<br/> '.img("r01.png",$lang['lumber']).'<span class="label label-success"> '.$prod[1].'/h </span><br/>'.LabelProdColor("res1", $res[1],$lim[1],0).'</td>
	<td> '.img("m02.jpg",$lang["stone"]).'<br/>'.img("r02.png",$lang['stone']).'<span class="label label-success"> '.$prod[2].'/h </span><br/>'.LabelProdColor("res2", $res[2],$lim[1],0).'</td>
	<td> '.img("m03.jpg",$lang["iron"]).'<br/>'.img("r03.png",$lang['iron']).'<span class="label label-success"> '.$prod[3].'/h </span><br/>'.LabelProdColor("res3", $res[3],$lim[1],0).'</td>
	<td> '.img("m04.jpg",$lang["gold"]).'<br/>'.img("r04.png",$lang['gold']).'<span class="label label-success"> '.$prod[4].'/h </span><br/>'.LabelProdColor("res4", $res[4],$lim[2],0).'</td>
	<td> '.img("m05.jpg",$lang["upkeep"]).'<br/>'.img("upk.png",$lang['upkeep'])." ".LabelColor(($town[3]+$town[12]),$lim[3],0).'<br/></td>
	<td> '.img("m06.jpg",$lang["Morale"]).'<br/>'.img("morale.png",$lang['Morale']).' <span class="label label-success">'.$town[5].'%</span></td>
	</tr><tr>';
				
	 */
	 
	$output .= "<td width='20%'>".img("menu_msg.jpg","Resources")."</td>";
	$output .= "<td width='20%'>".img("menu_gov.jpg","Resources")."</td>";
	$output .= "<td width='20%'>".img("menu_res.jpg","Resources")."</td>";
	$output .= "<td width='20%'>".img("menu_storage.jpg","Storage")."</td>";
	$output .= "<td width='20%'>".img("menu_troop.jpg","Army")."</td>";
	$output .= "<td width='20%'>".img("menu_support.jpg","Support And Research")."</td>";
	$output .= "<td width='20%'>".img("menu_infra.jpg","Infrastructure")."</td>";
	$output .= "</tr><tr><td>";
	/*
	 * RESOURCES
	 * */
	if ($data[8])
	{

		$output .= tdlink("house.php?town=".$town[0],$buildings[8][2],$data[8]);
		// echo "<a href='marketplace.php?town=".$town[0]."' onmouseout=\".src='".$imgs.$fimgs."b10.png', showtext('-')\" onmouseover=\"marketplace.src='".$imgs.$fimgs."b10_.png', showtext('".$buildings[10][2]." ".$lang['level']." ".$data[10]."</a>";}
	}
	if ($data[0])
	{
		$name=explode("-", $buildings[0][2]);
		$output .= tdlink("gmill.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[0][2]); echo "<a href='gmill.php?town=".$town[0]."'>$name[0]."</a>";}
	}
	if ($data[1])
	{

		$name=explode("-", $buildings[1][2]);
		$output .= tdlink("lmill.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[1][2]); echo "<a href='lmill.php?town=".$town[0]."' onmouseout=\"lmill.src='".$imgs.$fimgs."b1.png', showtext('-')\" onmouseover=\"lmill.src='".$imgs.$fimgs."b1_.png', showtext('".$name[0]."</a>";}
	}
	if ($data[2])
	{
		$name=explode("-", $buildings[2][2]);
		$output .= tdlink("smason.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[2][2]); echo "<a href='smason.php?town=".$town[0]."' onmouseout=\"smason.src='".$imgs.$fimgs."b2.png', showtext('-')\" onmouseover=\"smason.src='".$imgs.$fimgs."b2_.png', showtext('".$name[0]."</a>";}
	}
	if ($data[3])
	{
		$name=explode("-", $buildings[3][2]); // building = ore site, name0 = foundry
		$output .= tdlink("ifoundry.php?town=".$town[0],$name[0],10);
	}

	/*
	 * STORAGE
	 */
	$output .= "</td><td>";
	if ($data[10])
	{
		$output .= tdlink("marketplace.php?town=".$town[0],$buildings[10][2],$data[10]);
		//echo "<a href='house.php?town=".$town[0]."' onmouseout=\"house.src='".$imgs.$fimgs."b8.png', showtext('-')\" onmouseover=\"house.src='".$imgs.$fimgs."b8_.png', showtext('".$buildings[8][2]." ".$lang['level']." ".$data[8]."</a>";}
	}
	if ($data[4])
	{
		$output .= tdlink("granary.php?town=".$town[0],$buildings[4][2],$data[4]);
	}
	if ($data[5])
	{
		$output .= tdlink("warehouse.php?town=".$town[0],$buildings[5][2],$data[5]);
	}
	if ($data[21])
	{
		$output .= tdlink("wwarehouse.php?to=21&town=".$town[0],$buildings[21][2],$data[21]);
		// echo "<a href='wwarehouse.php?town=".$town[0]."' showtext('".$buildings[21][2]." ".$lang['level']." ".$data[21]."</a>";}
	}
	if ($data[6])
	{
		$output .= tdlink("cache.php?town=".$town[0],$buildings[6][2],$data[6]);
		//echo "<a href='cache.php?town=".$town[0]."' onmouseout=\"cache.src='".$imgs.$fimgs."b6.png', showtext('-')\" onmouseover=\"cache.src='".$imgs.$fimgs."b6_.png', showtext('".$buildings[6][2]." ".$lang['level']." ".$data[6].."</a>";
	}

	/*
	 * ARMY
	 */
	$output .= "</td><td>";
	if ($data[16])
	{
		$output .= tdlink("academy.php?town=".$town[0],$buildings[16][2],10);
	}
	if ($data[15])
	{
		$output .= tdlink("barracks.php?town=".$town[0],$buildings[15][2],$data[15]);
	}
	if ($data[19])
	{
		$output .= tdlink("stable.php?town=".$town[0],$buildings[19][2],$data[19]);
	}
	if ($data[14])
	{
		$output .= tdlink("tower.php?town=".$town[0],$buildings[14][2],$data[14]);
		// echo "<a href='tower.php?town=".$town[0]."' onmouseout=\"tower.src='".$imgs.$fimgs."b14.png', showtext('-')\" onmouseover=\"tower.src='".$imgs.$fimgs."b14_.png', showtext('".$buildings[14][2]." ".$lang['level']." ".$data[14]."</a>";}
	}
	if ($data[13])
	{
		$output .= tdlink("wall.php?town=".$town[0],$buildings[13][2],$data[13]);
	}

	/*
	 * MILITARY
	 */
	$output .= "</td><td>";

	$output .= tdlink("dispatch.php?town=".$town[0],$lang['crossroad'],10);

	if ($data[12])
	{
		$output .= tdlink("port.php?town=".$town[0],$buildings[12][2],$data[12]);
		//echo "<a href='port.php?town=".$town[0]."' onmouseout=\"porta.src='".$imgs.$fimgs."b12.png', showtext('-')\" onmouseover=\"porta.src='".$imgs.$fimgs."b12_.png', showtext('".$buildings[12][2]." ".$lang['level']." ".$data[12]."</a>";
	}
	if ($data[18])
	{
		$output .= tdlink("washop.php?to=18&town=".$town[0],$buildings[18][2],$data[18]);
	}
	if ($data[17])
	{
		$output .= tdlink("go.php?town=".$town[0],$buildings[17][2],10);
		//echo "<a href='go.php?to=17&town=".$town[0]."' onmouseout=\"blacksmith.src='".$imgs.$fimgs."b17.png', showtext('-')\" onmouseover=\"blacksmith.src='".$imgs.$fimgs."b17_.png', showtext('".$buildings[17][2]."</a>";}
	}
	if ($data[20])
	{
		$output .= tdlink("sshop.php?to=21&town=".$town[0],$buildings[20][2],$data[20]);
		//echo "<a href='sshop.php?town=".$town[0]."' onmouseout=\"sshop.src='".$imgs.$fimgs."b20.png', showtext('-')\" onmouseover=\"sshop.src='".$imgs.$fimgs."b20_.png', showtext('".$buildings[20][2]." ".$lang['level']." ".$data[20]."</a>";
	}
	$output .= tdlink("maptown.php?town=".$town[0],$lang['map'],10);
	/*
	 * INFRASTRUCTURE
	 */
	$output .= "</td><td>";
	if ($data[11])
	{
		$output .= tdlink("cathedral.php?town=".$town[0],$buildings[11][2],$data[11]);
		// echo "<a href='cathedral.php?town=".$town[0]."' onmouseout=\"cathedral.src='".$imgs.$fimgs."b11.png', showtext('-')\" onmouseover=\"cathedral.src='".$imgs.$fimgs."b11_.png', showtext('".$buildings[11][2]." ".$lang['level']." ".$data[11]."</a>";}
	}
	if ($data[9])
	{
		$output .= tdlink("embassy.php?town=".$town[0],$buildings[9][2],10);
		// echo "<a href='embassy.php?town=".$town[0]."' onmouseout=\"embassy.src='".$imgs.$fimgs."b9.png', showtext('-')\" onmouseover=\"embassy.src='".$imgs.$fimgs."b9_.png', showtext('".$buildings[9][2]."</a>";}
	}

	$output .= tdlink("hall.php?town=".$town[0],$buildings[7][2],$data[7]);
	$output .= tdlink("town_edit.php?town=".$town[0],"Town Name",10);

	$output .= tdlink("towns.php","Towns List",10);

	/*
	 * OTHERS
	 */
	/*
	 $output .= "</td></tr><tr><td colspan='5'><hr>".img("link.png", "Links");
	 $output .= "<a href='town_edit.php?town=".$town[0]."'>".preg_replace("/'/","\'",$town[2])."</a>";
	 */
	$output .= "</td></tr>";

	$output .= "</table></center>";
return $output;
}

function showoldmenu()
{

	$output .= "\n<center><table class='prod' border='1'><tr>";
	/*if ($data[7]) {$name=explode("-", $buildings[7][2]); if ($data[7]==10) {$i=22; $j=1;} else {$i=7; $j=0;} echo "<area shape='rect' coords='334,105,409,185' style='cursor:url(".$imgs.$fimgs."cursor.png), auto;' href='hall.php?town=".$town[0]."' onmouseout=\"hall.src='".$imgs.$fimgs."b".$i.".png', showtext('-')\" onmouseover=\"hall.src='".$imgs.$fimgs."b".$i."_.png', showtext('".$name[$j]." ".$lang['level']." ".$data[7]."')\">";}

	*/
	/*
	 $output .= "<td width='20%'>".img("item003.jpg",$lang['Morale'])."".img("level.png",$lang['level'])."Resources</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Storage</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Army</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Support And Research</td>";
	 $output .= "<td width='20%'>".img("level.png",$lang['level'])."Infrastructure</td>";
	 */
	/*
	 * RESOURCES
	 * */
	if ($data[8])
	{

		$output .= tdlink("house.php?town=".$town[0],$buildings[8][2],$data[8]);
		// echo "<a href='marketplace.php?town=".$town[0]."' onmouseout=\".src='".$imgs.$fimgs."b10.png', showtext('-')\" onmouseover=\"marketplace.src='".$imgs.$fimgs."b10_.png', showtext('".$buildings[10][2]." ".$lang['level']." ".$data[10]."</a>";}
	}
	if ($data[0])
	{
		$name=explode("-", $buildings[0][2]);
		$output .= tdlink("gmill.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[0][2]); echo "<a href='gmill.php?town=".$town[0]."'>$name[0]."</a>";}
	}
	if ($data[1])
	{

		$name=explode("-", $buildings[1][2]);
		$output .= tdlink("lmill.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[1][2]); echo "<a href='lmill.php?town=".$town[0]."' onmouseout=\"lmill.src='".$imgs.$fimgs."b1.png', showtext('-')\" onmouseover=\"lmill.src='".$imgs.$fimgs."b1_.png', showtext('".$name[0]."</a>";}
	}
	if ($data[2])
	{
		$name=explode("-", $buildings[2][2]);
		$output .= tdlink("smason.php?town=".$town[0],$name[0],10);
		//$name=explode("-", $buildings[2][2]); echo "<a href='smason.php?town=".$town[0]."' onmouseout=\"smason.src='".$imgs.$fimgs."b2.png', showtext('-')\" onmouseover=\"smason.src='".$imgs.$fimgs."b2_.png', showtext('".$name[0]."</a>";}
	}
	if ($data[3])
	{
		$name=explode("-", $buildings[3][2]); // building = ore site, name0 = foundry
		$output .= tdlink("ifoundry.php?town=".$town[0],$name[0],10);
	}

	/*
	 * STORAGE
	 */
	$output .= "</td><td>";
	if ($data[10])
	{
		$output .= tdlink("marketplace.php?town=".$town[0],$buildings[10][2],$data[10]);
		//echo "<a href='house.php?town=".$town[0]."' onmouseout=\"house.src='".$imgs.$fimgs."b8.png', showtext('-')\" onmouseover=\"house.src='".$imgs.$fimgs."b8_.png', showtext('".$buildings[8][2]." ".$lang['level']." ".$data[8]."</a>";}
	}
	if ($data[4])
	{
		$output .= tdlink("granary.php?town=".$town[0],$buildings[4][2],$data[4]);
	}
	if ($data[5])
	{
		$output .= tdlink("warehouse.php?town=".$town[0],$buildings[5][2],$data[5]);
	}
	if ($data[21])
	{
		$output .= tdlink("wwarehouse.php?to=21&town=".$town[0],$buildings[21][2],$data[21]);
		// echo "<a href='wwarehouse.php?town=".$town[0]."' showtext('".$buildings[21][2]." ".$lang['level']." ".$data[21]."</a>";}
	}
	if ($data[6])
	{
		$output .= tdlink("cache.php?town=".$town[0],$buildings[6][2],$data[6]);
		//echo "<a href='cache.php?town=".$town[0]."' onmouseout=\"cache.src='".$imgs.$fimgs."b6.png', showtext('-')\" onmouseover=\"cache.src='".$imgs.$fimgs."b6_.png', showtext('".$buildings[6][2]." ".$lang['level']." ".$data[6].."</a>";
	}

	/*
	 * ARMY
	 */
	$output .= "</td><td>";
	if ($data[16])
	{
		$output .= tdlink("academy.php?town=".$town[0],$buildings[16][2],10);
	}
	if ($data[15])
	{
		$output .= tdlink("barracks.php?town=".$town[0],$buildings[15][2],$data[15]);
	}
	if ($data[19])
	{
		$output .= tdlink("stable.php?town=".$town[0],$buildings[19][2],$data[19]);
	}
	if ($data[14])
	{
		$output .= tdlink("tower.php?town=".$town[0],$buildings[14][2],$data[14]);
		// echo "<a href='tower.php?town=".$town[0]."' onmouseout=\"tower.src='".$imgs.$fimgs."b14.png', showtext('-')\" onmouseover=\"tower.src='".$imgs.$fimgs."b14_.png', showtext('".$buildings[14][2]." ".$lang['level']." ".$data[14]."</a>";}
	}
	if ($data[13])
	{
		$output .= tdlink("wall.php?town=".$town[0],$buildings[13][2],$data[13]);
	}

	/*
	 * MILITARY
	 */
	$output .= "</td><td>";

	$output .= tdlink("dispatch.php?town=".$town[0],$lang['crossroad'],10);

	if ($data[12])
	{
		$output .= tdlink("port.php?town=".$town[0],$buildings[12][2],$data[12]);
		//echo "<a href='port.php?town=".$town[0]."' onmouseout=\"porta.src='".$imgs.$fimgs."b12.png', showtext('-')\" onmouseover=\"porta.src='".$imgs.$fimgs."b12_.png', showtext('".$buildings[12][2]." ".$lang['level']." ".$data[12]."</a>";
	}
	if ($data[18])
	{
		$output .= tdlink("washop.php?to=18&town=".$town[0],$buildings[18][2],$data[18]);
	}
	if ($data[17])
	{
		$output .= tdlink("go.php?town=".$town[0],$buildings[17][2],10);
		//echo "<a href='go.php?to=17&town=".$town[0]."' onmouseout=\"blacksmith.src='".$imgs.$fimgs."b17.png', showtext('-')\" onmouseover=\"blacksmith.src='".$imgs.$fimgs."b17_.png', showtext('".$buildings[17][2]."</a>";}
	}
	if ($data[20])
	{
		$output .= tdlink("sshop.php?to=21&town=".$town[0],$buildings[20][2],$data[20]);
		//echo "<a href='sshop.php?town=".$town[0]."' onmouseout=\"sshop.src='".$imgs.$fimgs."b20.png', showtext('-')\" onmouseover=\"sshop.src='".$imgs.$fimgs."b20_.png', showtext('".$buildings[20][2]." ".$lang['level']." ".$data[20]."</a>";
	}
	$output .= tdlink("maptown.php?town=".$town[0],$lang['map'],10);
	/*
	 * INFRASTRUCTURE
	 */
	$output .= "</td><td>";
	if ($data[11])
	{
		$output .= tdlink("cathedral.php?town=".$town[0],$buildings[11][2],$data[11]);
		// echo "<a href='cathedral.php?town=".$town[0]."' onmouseout=\"cathedral.src='".$imgs.$fimgs."b11.png', showtext('-')\" onmouseover=\"cathedral.src='".$imgs.$fimgs."b11_.png', showtext('".$buildings[11][2]." ".$lang['level']." ".$data[11]."</a>";}
	}
	if ($data[9])
	{
		$output .= tdlink("embassy.php?town=".$town[0],$buildings[9][2],10);
		// echo "<a href='embassy.php?town=".$town[0]."' onmouseout=\"embassy.src='".$imgs.$fimgs."b9.png', showtext('-')\" onmouseover=\"embassy.src='".$imgs.$fimgs."b9_.png', showtext('".$buildings[9][2]."</a>";}
	}

	$output .= tdlink("hall.php?town=".$town[0],$buildings[7][2],$data[7]);
	$output .= tdlink("town_edit.php?town=".$town[0],"Town Name",10);

	$output .= tdlink("towns.php","Towns List",10);

	/*
	 * OTHERS
	 */
	/*
	 $output .= "</td></tr><tr><td colspan='5'><hr>".img("link.png", "Links");
	 $output .= "<a href='town_edit.php?town=".$town[0]."'>".preg_replace("/'/","\'",$town[2])."</a>";
	 */
	$output .= "</td></tr>";

	$output .= "</table></center>";
	return $output;
}

function clean($str)
{
	global $db_id;
	if (is_numeric($str)) $str=floor($str);
	$cleaned=strip_tags($str);
	$cleaned=htmlspecialchars($cleaned);
	$cleaned=mysqli_real_escape_string($db_id, $cleaned);
	$to_clean=array("%20", "\"", "'", "\\", "=", ";", ":");
	$cleaned=str_replace($to_clean, "", $cleaned);
	return $cleaned;
}

function gen_stats($dur)
{
	global $db_id;

	$query="SELECT count(*) FROM users";
	$result=mysqli_query($db_id, $query);
	$row[0]=mysqli_fetch_row($result);
	$query="SELECT count(*) FROM users where hour(timediff(now(), lastVisit))<".$dur;
	$result=mysqli_query($db_id, $query);
	$row[1]=mysqli_fetch_row($result);

	return $row;
}

function clean_u($dur)
{
	global $db_id;

	$query="SELECT id FROM users where hour(timediff(now(), lastVisit))/24>".$dur;
	$result=mysqli_query($db_id, $query);
	 $nr=0;
	for (; $row=mysqli_fetch_row($result); $nr++) del_u($row[0]);

	return $nr;
}

function town_stats($col)
{
	global $db_id;

	$query="SELECT * from towns order by ".$col." desc";
	$result=mysqli_query($db_id, $query); $town_stats=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $town_stats[$i]=$row;

	return $town_stats;
}

function user_stats($col)
{
	global $db_id;

	$query="select id, name, (select sum(".$col.") from towns where owner=users.id) from users order by (select sum(".$col.") from towns where owner=users.id) desc";
	$result=mysqli_query($db_id, $query); $user_stats=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $user_stats[$i]=$row;

	return $user_stats;
}

function alliance_stats($col)
{
	global $db_id;

	$query="select id, name, (select sum(".$col.") from towns where owner in (select id from users where alliance=alliances.id)) from alliances order by (select sum(".$col.") from towns where owner in (select id from users where alliance=alliances.id)) desc";
	$result=mysqli_query($db_id, $query); $alliance_stats=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $alliance_stats[$i]=$row;

	return $alliance_stats;
}

function is_user($name, $email, $ip)
{
	global $db_id;

	$query="select count(*) from users where name='".$name."' or email='".$email."' or ip='".$ip."'";
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row[0];
}

function login($name, $pass)
{
	global $db_id;

	$query="select * from users where name='".$name."' and pass='".$pass."' and level>0";
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}

function sitted($account, $sitter)
{
	global $db_id;

	$query="select * from users where name='".$account."' and sitter='".$sitter."' and level>0";
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}

function user($id)
{
	global $db_id;

	$query="select * from users where id=".preg_replace("/[^0-9]/","", $id);
	$result=mysqli_query($db_id, $query);
	if ($result)
	{
		$row=mysqli_fetch_row($result);
		$row[1]=stripslashes($row[1]); $row[9]=stripslashes($row[9]);
		return $row;
	} else return 0;
}

function users()
{
	global $db_id;

	$query="select * from users";
	$result=mysqli_query($db_id, $query); $users=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$users[$i]=$row;
		$users[$i][1]=stripslashes($users[$i][9]); $users[$i][9]=stripslashes($users[$i][9]);
	}
	return $users;
}

function user_($name)
{
	global $db_id;

	$query="select * from users where name='".$name."'";
	$result=mysqli_query($db_id, $query);

	if ($result)
	{
		$row=mysqli_fetch_row($result);
		$row[1]=stripslashes($row[1]); $row[9]=stripslashes($row[9]);
		return $row;
	} else return 0;
}

function config()
{
	global $db_id;

	$config=array();
	$query="select * from config order by ord asc";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $config[$i]=$row;
	return $config;
}

function config_($var, $val)
{
	global $db_id;

	$query="update config set value='".$val."' where name='".$var."'";
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function g_points($names, $q)
{
	global $db_id;

	$query="update users set points=points+".$q." where name in (".$names.")";
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function alliance_all($id)
{
	global $db_id;

	$query="select * from alliances where id=".$id;
	$result=mysqli_query($db_id, $query); $alliance=array();
	$alliance[0]=mysqli_fetch_row($result);
	if (!$alliance[0][0]) { return 0;}
	$query="select * from users where alliance=".$alliance[0][0];
	$result=mysqli_query($db_id, $query);
	for ($i=0; $alliance[1][$i]=mysqli_fetch_row($result); $i++) ;
	$query="select * from pacts where type=0 and (a1=".$alliance[0][0]." or a2=".$alliance[0][0].")";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $alliance[2][$i]=mysqli_fetch_row($result); $i++) ;
	$query="select * from pacts where type=1 and (a1=".$alliance[0][0]." or a2=".$alliance[0][0].")";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $alliance[3][$i]=mysqli_fetch_row($result); $i++) ;

	return $alliance;
}

function alliance_($name)
{
	global $db_id;

	$query="select * from alliances where name='".$name."'";
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}

function alliance($id)
{
	global $db_id;

	$query="select * from alliances where id='".$id."'";
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}

function forum_pruning()
{
	global $db_id;

	$query="select id from forums where parent not in (select id from forums) and parent!=0";
	$result=mysqli_query($db_id, $query); $nr=0;
	for ($i=0; $row=mysqli_fetch_row($result); $i++) {forum(3, $row[$i][0], 0, 0, 0, 0); $nr++;}
	return $nr;
}

function forum($a, $id, $alliance, $parent, $name, $desc)
{
	global $db_id;

	switch($a)
	{
		case '0'://read
			$forums=array();
			$query="select * from forums where alliance=".$alliance." and parent=".$parent." order by name";
			$result=mysqli_query($db_id, $query);
			for ($i=0; $row=mysqli_fetch_row($result); $i++)
			{
				$forums[0][$i]=$row;
				$query="select count(*) from threads where forum=".$forums[0][$i][0];
				$row=mysqli_fetch_row(mysqli_query($query, $db_id));
				$forums[0][$i][5]=$row[0];
			}
			$query="select parent from forums where id=".$parent;
			$result=mysqli_query($db_id, $query); $row=mysqli_fetch_row($result);
			if ($row[0]) $forums[1]=$row[0]; else $forums[1]=0;
			return $forums;
			break;
		case '1'://add
			if ($name)
			{
				$query="insert into forums (alliance, parent, name, description) values (".$alliance.", ".$parent.", '".$name."', '".$desc."')";
				$result=mysqli_query($db_id, $query);
				if ($result) return 1; else return 0;
			} else return 0;
			break;
		case '2'://edit
			$query="update forums set parent=".$parent.", name='".$name."', description='".$desc."' where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
		case '3'://delete
			$query="delete from posts where thread in (select id from threads where forum=".$id.")";
			$result=mysqli_query($db_id, $query);
			$query="delete from threads where forum=".$id;
			$result=mysqli_query($db_id, $query);
			$query="delete from forums where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
	}
}

function thread($a, $id, $forum, $author, $name, $desc, $content)
{
	global $db_id;

	switch($a)
	{
		case '0'://read
			if (!$id)
			{
				$threads=array();
				$query="select * from threads where forum=".$forum." order by date";
				$result=mysqli_query($db_id, $query);
				for ($i=0; $row=mysqli_fetch_row($result); $i++)
				{
					$threads[$i]=$row;
					$query="select count(*) from posts where thread=".$threads[$i][0];
					$row=mysqli_fetch_row(mysqli_query($query, $db_id));
					$threads[$i][7]=$row[0];
				}
				return $threads;
			}
			else
			{
				$query="select * from threads where id=".$id;
				$thread=mysqli_fetch_row(mysqli_query($query, $db_id));
				return $thread;
			}
			break;
		case '1'://add
			if ($name)
			{
				$query="insert into threads (forum, author, date, name, description, content) values (".$forum.", ".$author.", now(), '".$name."', '".$desc."', '".$content."')";
				$result=mysqli_query($db_id, $query);
				if ($result) return 1; else return 0;
			} else return 0;
			break;
		case '2'://edit
			$query="update threads set forum=".$forum.", name='".$name."', description='".$desc."', content='".$content."', date=now() where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
		case '3'://delete
			$query="delete from posts where thread=".$id;
			$result=mysqli_query($db_id, $query);
			$query="delete from threads where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
	}
}

function post($a, $id, $thread, $author, $desc, $content)
{
	global $db_id;

	switch($a)
	{
		case '0'://read
			if (!$id)
			{
				$posts=array();
				$query="select * from posts where thread=".$thread." order by date";
				$result=mysqli_query($db_id, $query);
				for ($i=0; $row=mysqli_fetch_row($result); $i++) $posts[$i]=$row;
				return $posts;
			}
			else
			{
				$query="select * from posts where id=".$id;
				$post=mysqli_fetch_row(mysqli_query($query, $db_id));
				return $post;
			}
			break;
		case '1'://add
			if ($content)
			{
				$query="insert into posts (thread, author, date, description, content) values (".$thread.", ".$author.", now(), '".$desc."', '".$content."')";
				$result=mysqli_query($db_id, $query);
				if ($result) return 1; else return 0;
			} else return 0;
			break;
		case '2'://edit
			$query="update posts set description='".$desc."', content='".$content."', date=now() where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
		case '3'://delete
			$query="delete from posts where id=".$id;
			$result=mysqli_query($db_id, $query);
			if ($result) return 1; else return 0;
			break;
	}
}

function faction($id)
{
	global $db_id;

	$query="select * from factions where id=".$id;
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}

function factions()
{
	global $db_id;

	$factions=array();
	$query="select * from factions";
	$result=mysqli_query($db_id, $query);

	for ($i=0; $row=mysqli_fetch_row($result); $i++) $factions[$i]=$row;
	return $factions;
}

function town($id)
{
	global $db_id;
		$loc=town_xy($id);
 //$query="update towns set x='".$loc[0]."', y='".$loc[1]."' where id=".$id;
	//mysqli_query($db_id, $query);
	$query="select * from towns where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result)
	{
		$row = mysqli_fetch_array($result, MYSQLI_BOTH);
		if($row)
		{
		//$row=mysqli_fetch_row($result);
		$row[2]=stripslashes($row[2]); 
		$row[14]=stripslashes($row[14]);
		return $row;
		}
		else 
		{
			return 0;
		}
	} 
	else 
	{
		return 0;
	}
}

function town_($name)
{
	global $db_id;

	$query="select * from towns where name='".$name."'";
	$result=mysqli_query($db_id, $query);

	if ($result)
	{
		$row=mysqli_fetch_row($result);
		$row[2]=stripslashes($row[2]); $row[14]=stripslashes($row[14]);
		return $row;
	} else return 0;
}

function town_xy($id)
{
	global $db_id;
 $row = "";
	$query="select * from map where townsid=".$id;
	$result=mysqli_query($db_id, $query );
	if ($result = mysqli_query($db_id, $query))
	{
	$row=mysqli_fetch_row($result);
	}
	return $row;
}

function towns($id)
{
	global $db_id;
	//$query="select * from towns where owner=".$id." AND isCapital = 1 order by isCapital desc";
	//$result=mysqli_query($db_id, $query);
	//$towns=array();
	//$towns[0]=$row;
	//$towns[0][2]=stripslashes($row[2]);
	//$towns[0][14]=stripslashes($row[14]);

	$query="select * from towns where owner=".$id." ORDER BY isCapital ASC;";
	$result=mysqli_query($db_id, $query);
	//$row=mysqli_fetch_row($result);
$towns = "";
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$towns[$i]=$row;
		$towns[$i][2]=stripslashes($row[2]);
		$towns[$i][14]=stripslashes($row[14]);
	}
	return $towns;
}

function buildings($faction)
{
	global $db_id, $lang;

	$query="select * from buildings where faction=".$faction;
	$result=mysqli_query($db_id, $query); $buildings=array();

	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$buildings[$i]=$row;
		if (isset($lang['buildings']))
		{
			$buildings[$i][2]=$lang['buildings'][$faction-1][$i][0];
			$buildings[$i][8]=$lang['buildings'][$faction-1][$i][1];
		}
	}
	return $buildings;
}

function weapons($faction)
{
	global $db_id, $lang;

	$query="select * from weapons where faction=".$faction;
	$result=mysqli_query($db_id, $query); $weapons=array();

	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$weapons[$i]=$row;
		if (isset($lang['weapons']))
		{
			$weapons[$i][2]=$lang['weapons'][$faction-1][$i][0];
			$weapons[$i][5]=$lang['weapons'][$faction-1][$i][1];
		}
	}
	return $weapons;
}

function units($faction)
{
	global $db_id, $lang;

	$query="select * from units where faction=".$faction;
	$result=mysqli_query($db_id, $query); $units=array();

	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$units[$i]=$row;
		if (isset($lang['units']))
		{
			$units[$i][2]=$lang['units'][$faction-1][$i][0];
			$units[$i][10]=$lang['units'][$faction-1][$i][1];
		}
	}
	return $units;
}

function get_land()
{
	global $db_id;

	$query="select x, y from map where type=1";
	$result=mysqli_query($db_id, $query);

	for ($i=0; $row=mysqli_fetch_row($result); $i++) $land[$i]=$row;
	return $land;
}

function map($x, $y)
{
	global $db_id;
	global $mapsize;
	// mapsize is defined in map_php
	$query="select * from map where (y between ".($y-$mapsize)." and ".($y+$mapsize).")  and (x between ".($x-$mapsize)." and ".($x+$mapsize).") order by y desc, x asc";
	$result=mysqli_query($db_id, $query);
	$data=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{ 
		$data[$i]=$row;
	}
	return $data;
}

function sector($x, $y)
{
	global $db_id;

	$query="select * from map where x=".$x." and y=".$y;
	$result=mysqli_query($db_id, $query);

	$row=mysqli_fetch_row($result);
	return $row;
}


function map_imgold($data, $x, $y, &$i, $imgs)
{
	echo "src='".$imgs."map/";
	if (isset($data[$i][0]))
	{
		if (($data[$i][0]==$x)&&($data[$i][1]==$y))
		{
			if ($data[$i][2]==3)
			{
				$town=town($data[$i][3]);
				if ($town[3]<=100) echo "3-0000-0";

				// if ($town[3]<=100) echo "31";
				// if upgraded
				// else if (($town[3]>100)&&($town[3]<=200)) echo "32";
				// else if (($town[3]>200)&&($town[3]<=300)) echo "33";
				// else if ($town[3]>300) echo "34";
			}
			// mountain
			else if ($data[$i][2]==2) echo $data[$i][2]."-9999-0";//.rand(0, 9);
			//   //else if (!$data[$i][2]) echo $data[$i][2]."-".$data[$i+1][2]."00".$data[$i-1][2]."-".rand(0, 9);//"0"."-".
			else echo $data[$i][2]."-".$data[$i-1][2]."0".$data[$i+1][2]."0-".rand(0, 9);//"0"."-".   echo $data[$i][2].$data[$i][3];
			if ($i<count($data)-1) $i++;
		}
		else echo "x";
		echo ".png'";
	}
	else echo "x.png'";
}

function map_img($data, $x, $y, &$i, $imgs)
{
	//echo "src='".$imgs."map/env_";
	echo "src='".$imgs."map/lib/";
	if (isset($data[$i]))
	{
		if (($data[$i][0]==$x)&&($data[$i][1]==$y))
		{
			if ($data[$i][7]!=0)     //if ($data[$i][2]==3) 
			{ // this is town
				if($data[$i][8] == 1) // a capital!
				{
					$town=town($data[$i][3]);
					if ($town[3]<=100)
					{
						echo "31";
					}
					else if (($town[3]>100)&&($town[3]<=200))
					{
						echo "32";
					}
					else if (($town[3]>200)&&($town[3]<=300))
					{
						echo "33";
					}
					else if ($town[3]>300)
					{
						echo "34";
					}
				} // capital end
				
				if($data[$i][8] > 1) // a capital!
				{
					//depends on db data result
				// 2 - housing
				// 3 - farm/grain mill
				// 4 - lumber
				// 5 - mine
				// 6 - farmcow
					echo "2".$data[$i][8]; 
				}
			}
			else if ($data[$i][2]>=5)
			{
				echo "3".$data[$i][2];
			}
			else
			{// peta
				/*
				 if ($data[$i][3] < 6)
				 {
					$seed = $data[$i][3];
					}
					else
					{
					$seed = $data[$i][3] - 6;
					}*/
				/*	$seed = $data[$i][3];
				 $gambarpeta = $data[$i][4].$seed;

				 if ($data[$i][2] == 2)
				 {
					$gambarpeta =
					$data[$i][2].
					$data[$i][2].
					$data[$i][2].
					$data[$i][2].
					$data[$i][2].
					$data[$i][3];
					}*/
				/*$gambarpeta .= $data[$i][2];
				 $gambarpeta .= mapimg($data,$i);
				 $gambarpeta .= $data[$i][2];
				 $gambarpeta .= mapimg($data,$i);*/
				if ($data[$i][2] == 0)
				{
					$gambarpeta = "0";
					if ($data[$i][4][1] != 0 )
					{
						$gambarpeta = $data[$i][4];
					}
					if ($data[$i][4][2] != 0 )
					{
						$gambarpeta = $data[$i][4];
					}
					if ($data[$i][4][3] != 0 )
					{
						$gambarpeta = $data[$i][4];
					}
					if ($data[$i][4][4] != 0 )
					{
						$gambarpeta = $data[$i][4];
					}
					//$gambarpeta = "0";
				}
				if ($data[$i][2] == 1)
				{
					$gambarpeta = $data[$i][4];
					if(
					$data[$i][4][1] == 1 ||
					$data[$i][4][2] == 1 ||
					$data[$i][4][3] == 1 ||
					$data[$i][4][4] == 1)
					{
						$gambarpeta = "1".$data[$i][3];
					}
					if(
					$data[$i][4][1] == 2 ||
					$data[$i][4][2] == 2 ||
					$data[$i][4][3] == 2 ||
					$data[$i][4][4] == 2)
					{
						$gambarpeta = "2".$data[$i][3];
					}
				}
				if ($data[$i][2] == 2)
				{
					$gambarpeta = "2".$data[$i][3];

				}
				/*	if ($data[$i][2] == 1)
				 {
					$gambarpeta = "11111".$data[$i][3];
					if($data[$i+1][2] == 2)
					{
					$gambarpeta = "12010".$data[$i][3];
					}
					if($data[$i-1][2] == 2)
					{
					$gambarpeta = "12010".$data[$i][3];
					}
					}
					if ($data[$i][2] == 2)
					{
					$gambarpeta = "22222".$data[$i][3];
					}*/
				echo "/".$data[$i][2] ."/". $gambarpeta;
			}
			if ($i<count($data)-1) $i++;
		}
		else 
		{
			echo "x";
		}
		echo ".png'";
	}
	else 
		{
			echo "x.png";
		}
}
function mapimg($data,$i)
{
	$gambarpeta = $data[$i][2];
	if($data[$i][2] == 0)
	{
		if($data[$i+1][2] == 2)
		{
			$gambarpeta = $data[$i+1][2];
		}
		else
		{
			$gambarpeta = $data[$i][2];
		}
	}
	if($data[$i][2] == 1)
	{
		if($data[$i+1][2] == 2)
		{
			$gambarpeta = $data[$i+1][2];
		}
		if($data[$i-1][2] == 2)
		{
			$gambarpeta = $data[$i-1][2];
		}
		else
		{
			$gambarpeta = $data[$i][2];
		}
	}
	return $gambarpeta;
}
function map_lnk($data, $x, $y, &$i)
{
	if (isset($data[$i][0]))
	{
		if (($data[$i][0]==$x)&&($data[$i][1]==$y))
		{
			if ($data[$i][2]>=3)
			{
				$town=town($data[$i][3]);
				if ($town[1])
				{
					$usr=user($town[1]); $alliance=alliance($usr[11]);
					if (isset($_SESSION["user"][0])) $towns=towns($_SESSION["user"][0]); else $towns[0][0]=0;
					echo "href=\"javascript: xmenu(".$usr[0].", ".$town[0].", ".$towns[0][0].")\" onMouseOver=\"desc('".$town[2]."', '".$usr[1]."', '".$town[3]."', '".$alliance[1]."')\" onMouseOut=\"desc('Description', '', '', '')\"";
				}
				else echo "href='aquire.php?id=".$town[0]."' onMouseOver=\"desc('".$town[2]."', '[abandoned]', '".$town[3]."', '')\" onMouseOut=\"desc('Description', '', '', '')\"";
			}
			else if (!$data[$i][2]) echo "href=\"javascript: template('map_.php', 'x=".$x."&y=".$y."')\" onMouseOver=\"desc('Water-".$data[$i][5]."', '".$data[$i][4]."-".$data[$i][3]."', '-', '-')\" onMouseOut=\"desc('Description', '', '', '')\"";
			else if ($data[$i][2]==2) echo "href=\"javascript: template('map_.php', 'x=".$x."&y=".$y."')\" onMouseOver=\"desc('Mountains-".$data[$i][5]."', '".$data[$i][4]."-".$data[$i][3]."', '-', '-')\" onMouseOut=\"desc('Description', '', '', '')\"";
			else if ($data[$i][2]==1) echo "href=\"javascript: template('map_.php', 'x=".$x."&y=".$y."')\" onMouseOver=\"desc('Land-".$data[$i][5]."', '".$data[$i][4]."-".$data[$i][3]."', '-', '-')\" onMouseOut=\"desc('Description', '', '', '')\"";
			if ($i<count($data)-1) $i++;
		}
		else echo "href=\"javascript: template('map_.php', 'x=".$x."&y=".$y."')\" onMouseOver=\"desc('void', '-', '-', '-')\" onMouseOut=\"desc('Description', '', '', '')\"";
	}
	else echo "href=\"javascript: template('map_.php', 'x=".$x."&y=".$y."')\" onMouseOver=\"desc('void', '-', '-', '-')\" onMouseOut=\"desc('Description', '', '', '')\"";
}

function update_lastVisit($id)
{
	global $db_id;

	$query="select count(*) from reports where recipient=".$id." and timediff((select lastVisit from users where id=".$id."), sent)<'00:00:01'";
	$result=mysqli_query($db_id, $query);
	$row[0]=mysqli_fetch_row($result); $row[0]=$row[0][0];
	$query="select count(*) from messages where recipient=".$id." and timediff((select lastVisit from users where id=".$id."), sent)<'00:00:01'";
	$result=mysqli_query($db_id, $query);
	$row[1]=mysqli_fetch_row($result); $row[1]=$row[1][0];
	$query="update users set lastVisit=now(), ip='".$_SERVER["REMOTE_ADDR"]."' where id=".$id;
	mysqli_query($db_id, $query);

	return $row;
}

function update_taxes($production, $morale, $id)
{
	global $db_id;

	$query="update towns set production='".$production."', morale=".$morale." where id=".$id;
	mysqli_query($db_id, $query);
}

function update_formation($id, $gen)
{
	global $db_id;
	$town=town($id);

	$query="update towns set general='".$gen."' where id=".$id;
	$result=mysqli_query($db_id, $query);

	if ($result) header("Location: gen.php?town=".$id);
	else msg("Failed.".mysqli_error());
}

function update_town($name, $desc, $id)
{
	global $db_id;

	$query="select count(*) from towns where name='".$name."' and id!=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if (!$row[0])
	{
		$query="update towns set name='".$name."', description='".$desc."' where id=".$id;
		mysqli_query($db_id, $query);
	} else msg("Name taken.");
}

function purge($id)
{
	global $db_id;

	$query="update map set type=1, subtype=3 where type=3 and subtype=".$id;
	mysqli_query($db_id, $query);
	$query="delete from a_queue where a_queue.town=".$id." or a_queue.target=".$id;
	mysqli_query($db_id, $query);
	$query="delete from c_queue where c_queue.town=".$id;
	mysqli_query($db_id, $query);
	$query="delete from t_queue where t_queue.seller=".$id." or t_queue.buyer=".$id;
	mysqli_query($db_id, $query);
	$query="delete from u_queue where u_queue.town=".$id;
	mysqli_query($db_id, $query);
	$query="delete from uup_queue where uup_queue.town=".$id;
	mysqli_query($db_id, $query);
	$query="delete from w_queue where w_queue.town=".$id;
	mysqli_query($db_id, $query);
	$query="delete from towns where id=".$id;
	mysqli_query($db_id, $query);
}

function abandon($id)
{
	global $db_id;

	$query="update towns set owner=0 where id=".$id;
	mysqli_query($db_id, $query);
}

function aquire($id, $owner)
{
	global $db_id;

	$query="update towns set owner=".$owner." where id=".$id;
	mysqli_query($db_id, $query);
}

function update_a($name, $desc, $id)
{
	global $db_id;

	$query="select count(*) from alliances where name='".$name."' and id!=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if (!$row[0])
	{
		$query="update alliances set name='".$name."', description='".$desc."' where id=".$id;
		mysqli_query($db_id, $query);
	} else msg("Name taken.");
}

function update_rank($id, $rank)
{
	global $db_id;

	$query="update users set rank='".$rank."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function check_d($id)
{
	global $db_id;

	$query="select timediff(dueTime, now()) from d_queue where user=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0][0])
	if ($row[0][0]=="-")
	{
		$query="update map set type=1, subtype=6 where subtype in (select id from towns where owner=".$id.")";
		mysqli_query($db_id, $query);
		$query="select id from alliances where founder=".$id;
		$result=mysqli_query($db_id, $query); $row=mysqli_fetch_row($result);
		if ($row[0])//if the user is an alliance founder
		{
			$query="delete from alliances where id=".$row[0];
			mysqli_query($db_id, $query);
			$query="delete from pacts where (a1=".$row[0]." or a2=".$row[0].")";
			mysqli_query($db_id, $query);
		}
		$query="delete from a_queue where (a_queue.town in (select id from towns where owner=".$id.") or a_queue.target in (select id from towns where owner=".$id."))";
		mysqli_query($db_id, $query);
		$query="delete from c_queue where c_queue.town in (select id from towns where owner=".$id.")";
		mysqli_query($db_id, $query);
		$query="delete from d_queue where user=".$id;
		mysqli_query($db_id, $query);
		$query="delete from t_queue where (t_queue.seller in (select id from towns where owner=".$id.") or t_queue.buyer in (select id from towns where owner=".$id."))";
		mysqli_query($db_id, $query);
		$query="delete from u_queue where u_queue.town in (select id from towns where owner=".$id.")";
		mysqli_query($db_id, $query);
		$query="delete from uup_queue where uup_queue.town in (select id from towns where owner=".$id.")";
		mysqli_query($db_id, $query);
		$query="delete from w_queue where w_queue.town in (select id from towns where owner=".$id.")";
		mysqli_query($db_id, $query);
		$query="delete from messages where recipient=".$id;
		mysqli_query($db_id, $query);
		$query="delete from reports where recipient=".$id;
		mysqli_query($db_id, $query);
		$query="delete from towns where owner=".$id;
		mysqli_query($db_id, $query);
		$query="delete from users where id=".$id;
		mysqli_query($db_id, $query);
		return 0;
	}
	return 1;
}

function del_u($id)
{
	global $db_id;

	$query="update map set type=1, subtype=6 where subtype in (select id from towns where owner=".$id.")";
	mysqli_query($db_id, $query);
	$query="select id from alliances where founder=".$id;
	$result=mysqli_query($db_id, $query); $row=mysqli_fetch_row($result);
	if ($row[0])//if the user is an alliance founder
	{
		$query="delete from alliances where id=".$row[0];
		mysqli_query($db_id, $query);
		$query="delete from pacts where (a1=".$row[0]." or a2=".$row[0].")";
		mysqli_query($db_id, $query);
	}
	$query="delete from a_queue where (a_queue.town in (select id from towns where owner=".$id.") or a_queue.target in (select id from towns where owner=".$id."))";
	mysqli_query($db_id, $query);
	$query="delete from c_queue where c_queue.town in (select id from towns where owner=".$id.")";
	mysqli_query($db_id, $query);
	$query="delete from d_queue where user=".$id;
	mysqli_query($db_id, $query);
	$query="delete from t_queue where (t_queue.seller in (select id from towns where owner=".$id.") or t_queue.buyer in (select id from towns where owner=".$id."))";
	mysqli_query($db_id, $query);
	$query="delete from u_queue where u_queue.town in (select id from towns where owner=".$id.")";
	mysqli_query($db_id, $query);
	$query="delete from uup_queue where uup_queue.town in (select id from towns where owner=".$id.")";
	mysqli_query($db_id, $query);
	$query="delete from w_queue where w_queue.town in (select id from towns where owner=".$id.")";
	mysqli_query($db_id, $query);
	$query="delete from messages where recipient=".$id;
	mysqli_query($db_id, $query);
	$query="delete from reports where recipient=".$id;
	mysqli_query($db_id, $query);
	$query="delete from towns where owner=".$id;
	mysqli_query($db_id, $query);
	$query="delete from users where id=".$id;
	mysqli_query($db_id, $query);
}

function check_r($id)
{
	global $db_id;

	$query="select production, resources, limits, timediff(now(), lastCheck), morale, upkeep, population from towns where id=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	$time=explode(":", $row[3]); $time=$time[0]+$time[1]/60+$time[2]/3600;
	$res=explode("-", $row[1]); $prod=explode("-", $row[0]); $lim=explode("-", $row[2]); $m=$row[4]/100;
	if ($prod[0]-$row[5]-$row[6]<5) $prod[0]=$row[5]+$row[6]+5;//noob protection against negative crop production values
	if ($res[0]+($prod[0]-$row[5]-$row[6])*$time*$m<=$lim[0])
	{
		$res[0]+=($prod[0]-$row[5]-$row[6])*$time*$m;
	}
	else
	{
		$res[0]=$lim[0];
	}
	if ($res[1]+$prod[1]*$time*$m<=$lim[1])
	{
		$res[1]+=$prod[1]*$time*$m;
	}
	else
	{
		$res[1]=$lim[1];
	}
	if ($res[2]+$prod[2]*$time*$m<=$lim[1])
	{
		$res[2]+=$prod[2]*$time*$m;
	}
	else
	{
		$res[2]=$lim[1];
	}
	if ($res[3]+$prod[3]*$time*$m<=$lim[1])
	{
		$res[3]+=$prod[3]*$time*$m;
	} else
	{
		$res[3]=$lim[1];
	}
	if ($res[4]+$prod[4]*$time<=$lim[2])
	{
		$res[4]+=$prod[4]*$time;
	}
	else
	{
		$res[4]=$lim[2];
	}
	$res=$res[0]."-".$res[1]."-".$res[2]."-".$res[3]."-".$res[4];

	$query="update towns set resources='".$res."', lastCheck=now() where id=".$id;
	$result=mysqli_query($db_id, $query);
}

function check_c($id, $faction)
{
	global $db_id, $tdif;
	$town=town($id);
	$buildings=buildings($faction);
	$data=explode("-", $town[8]); $res=explode("-", $town[10]); $lim=explode("-", $town[11]); $prod=explode("-", $town[9]); $land=explode("/", $town[13]);
	$land[0]=explode("-", $land[0]); $land[1]=explode("-", $land[1]); $land[2]=explode("-", $land[2]); $land[3]=explode("-", $land[3]);

	$query="select timediff(dueTime".$tdif.", now()), b, subB from c_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0][0]=="-")
	{
		if ($row[2]>-1)
		{
			$land[$row[1]][$row[2]]++; $ldata="";
			for ($i=0; $i<count($land); $i++) $ldata[$i]=implode("-", $land[$i]);
			$ldata=implode("/", $ldata);
			$out=explode("-", $buildings[$row[1]][5]); $prod[$row[1]]=0;
			for ($i=0; $i<count($land[$row[1]]); $i++)
			if ($land[$row[1]][$i]) $prod[$row[1]]+=$out[$land[$row[1]][$i]-1];
			$pdata=implode("-", $prod);
			$query="update towns set land='".$ldata."', production='".$pdata."' where id=".$id;
			mysqli_query($db_id, $query);
		}
		else switch($row[1])
		{
			case 0:
				{
					$data[$row[1]]=1; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 1:
				{
					$data[$row[1]]=1; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 2:
				{
					$data[$row[1]]=1; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 3:
				{
					$data[$row[1]]=1; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 4:
				{
					$data[4]++; $lim[0]=explode("-", $buildings[4][5]); $lim[0]=$lim[0][$data[4]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 5:
				{
					$data[5]++; $lim[1]=explode("-", $buildings[5][5]); $lim[1]=$lim[1][$data[5]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 6:
				{
					$data[6]++; $lim[5]=explode("-", $buildings[6][5]); $lim[5]=$lim[5][$data[6]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 7:
				{
					$data[7]++; $lim[4]=explode("-", $buildings[7][5]); $lim[4]=$lim[4][$data[7]-1]; $lim[2]+=800; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 8:
				{
					$data[8]++; $lim[3]=explode("-", $buildings[8][5]); $lim[3]=$lim[3][$data[8]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 9:
				{
					$data[9]++; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 10:
				{
					$data[10]++; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 11:
				{
					$mdata=explode("-", $buildings[11][5]);
					$data[11]++; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."', morale=".(100-$prod[4]+$mdata[$data[11]-1])." where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 12:
				{
					$data[12]++; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 13:
				{
					$data[13]++; $lim[6]=explode("-", $buildings[13][5]); $lim[6]=$lim[6][$data[13]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 14:
				{
					$data[14]++; $lim[7]=explode("-", $buildings[14][5]); $lim[7]=$lim[7][$data[14]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 15:
				{
					$data[15]++; $lim[8]=explode("-", $buildings[15][5]); $lim[8]=$lim[8][$data[15]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 16:
				{
					$data[16]=1; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 17:
				{
					$data[17]++; $bdata=implode("-", $data);
					$query="update towns set buildings='".$bdata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 18:
				{
					$data[18]++; $lim[9]=explode("-", $buildings[18][5]); $lim[9]=$lim[9][$data[18]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 19:
				{
					$data[19]++; $lim[10]=explode("-", $buildings[19][5]); $lim[10]=$lim[10][$data[19]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 20:
				{
					$data[20]++; $lim[11]=explode("-", $buildings[20][5]); $lim[11]=$lim[11][$data[20]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			case 21:
				{
					$data[21]++; $lim[12]=explode("-", $buildings[21][5]); $lim[12]=$lim[12][$data[21]-1]; $bdata=implode("-", $data); $ldata=implode("-", $lim);
					$query="update towns set buildings='".$bdata."', limits='".$ldata."' where id=".$id;
					mysqli_query($db_id, $query);
				} break;
			default: ;
		}
		$query="delete from c_queue where c_queue.town=".$id." and c_queue.b=".$row[1]." and c_queue.subB=".$row[2];
		mysqli_query($db_id, $query);
	}
}

function check_w($id)
{
	global $db_id, $tdif;
	$town=town($id);
	$data=explode("-", $town[6]);

	$query="select timediff(dueTime".$tdif.", now()), type, quantity from w_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0][0]=="-")
	{
		$data[$row[1]]+=$row[2]; $d=implode("-", $data);
		$query="update towns set weapons='".$d."' where id=".$id;
		mysqli_query($db_id, $query);
		$query="delete from w_queue where town=".$id." and type=".$row[1];
		mysqli_query($db_id, $query);
	}
}
function d($str)
{
	echo "<pre>".print_r($str,true)."</pre>";
}

//88888888888888888888888888888888888888888888888888888888888

function html_weaps($weaps)
{
	global $imgs, $fimgs;
	$html_data="<table class='q_table' style='border-collapse: collapse' width='600' border='1'><tr>";
	for ($i=0; $i<count($weaps); $i++) $html_data.="<td><img src='".$imgs.$fimgs."1".$i.".gif'></td>";
	$html_data.="</tr><tr>";
	for ($i=0; $i<count($weaps); $i++) $html_data.="<td>".$weaps[$i]."</td>";
	$html_data.="</tr></table>";

	return $html_data;
}

function html_res($res)
{
	global $imgs, $fimgs;
	$html_data="<table class='q_table' style='border-collapse: collapse' width='600' border='1'><tr>";
	for ($i=0; $i<count($res); $i++) $html_data.="<td><img height='25' src='".$imgs.$fimgs."0".$i.".gif'></td>";
	$html_data.="</tr><tr>";
	for ($i=0; $i<count($res); $i++) $html_data.="<td>".round($res[$i])."</td>";
	$html_data.="</tr></table>";

	return $html_data;
}

function html_army($army, $f)
{
	global $imgs, $fimgs;
	$units=units($f);
	$html_data="<table class='q_table' style='border-collapse: collapse' width='600' border='1'><tr>";
	for ($i=0; $i<count($army); $i++) $html_data.="<td><img height='25' src='".$imgs.$fimgs."2".$i.".gif' title='".$units[$i][2]."'></td>";
	$html_data.="</tr><tr>";
	for ($i=0; $i<count($army); $i++) $html_data.="<td>".$army[$i]."</td>";
	$html_data.="</tr></table>";

	return $html_data;
}

function check_a($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), town, target, type, phase, army, general, uup, wup, aup, rLoot, wLoot, intel, sent, dueTime, id from a_queue where town=".$id." or target=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query);
	for (; $line=mysqli_fetch_row($result); )
	if ($line[0][0]=="-")
	{
		$town=town($line[1]); $lim=explode("-", $town[11]);
		$to_owner=user($town[1]);
		$target=town($line[2]);
		$ta_owner=user($target[1]);
		check_r($target[0]);
		if ($target[0])//if the target town exists
		if ($line[3])//if it is not a reinforcement
		{
			$data[0][0]=$ta_owner[10]; $data[0][1]=explode("-", $target[7]); $data[0][2]=explode("-", $target[15]); $data[0][3]=explode("-", $target[8]); $data[0][4]=explode("-", $target[11]); $data[0][5]=explode("-", $target[10]); $data[0][6]=explode("-", $target[6]); $data[0][7]=explode("-", $target[17]); $data[0][8]=explode("-", $target[18]); $data[0][9]=explode("-", $target[19]);
			$data[1][0]=$to_owner[10]; $data[1][1]=explode("-", $line[5]); $data[1][2]=explode("-", $line[6]); $data[1][3]=explode("-", $line[7]); $data[1][4]=explode("-", $line[8]); $data[1][5]=explode("-", $line[9]);
			$data[2]=$line[3]; $data[3]=explode("-", $line[10]); $data[4]=explode("-", $line[11]); $data[5]=$line[12];
			if (!$line[4])//if phase 0
			{
				$data=battle($data); $siege_target=-1; $buildings=buildings($ta_owner[10]);
				$line[13]=explode("-", $line[13]);
				$date=strtotime("+".$line[13][0]." hours ".$line[13][1]." minutes", strtotime($line[14]));
				$date=strftime("%Y-%m-%d %H:%M:%S", $date);
				//population update due to possible siege damage
				if ($target[8]!=implode("-", $data[0][3]))
				{
					$target[8]=explode("-", $target[8]);
					for ($i=0; $i<22; $i++) if ($target[8][$i]>$data[0][3][$i])
					{
						$siege_target=$i;
						$buildings[$i][7]=explode("-", $buildings[$i][7]);
						$target[3]-=$buildings[$i][7][$target[8][$i]];
					}
				}

				if ($data[1][1][11]<100)
				{
					$query="update towns set population=".$target[3].", army='".implode("-", $data[0][1])."', upkeep=".array_sum($data[0][1]).", general='".implode("-", $data[0][2])."', buildings='".implode("-", $data[0][3])."', resources='".implode("-", $data[0][5])."', weapons='".implode("-", $data[0][6])."' where id=".$target[0];
					mysqli_query($db_id, $query);
				}
				else//if there are 100 or more colonists in attacking army
				{
					$data[1][1][11]-=100;
					$query="update towns set owner='".$to_owner[0]."', isCapital=0, population=".$target[3].", army='".implode("-", $data[0][1])."', upkeep=".array_sum($data[0][1]).", general='".implode("-", $data[0][2])."', buildings='".implode("-", $data[0][3])."', resources='".implode("-", $data[0][5])."', weapons='".implode("-", $data[0][6])."' where id=".$target[0];
					mysqli_query($db_id, $query);
					send_report($to_owner[0], "Congratulation, captured town!", "You have captured the town of ".$target[2].".");
					send_report($ta_owner[0], "Oh my, our town captured!", "The town ".$target[2]." has been captured by ".$town[2].".");
				}
				if (!$data[5]) $data[5]=array("[no info]");
				$query="update a_queue set phase=1, dueTime='".$date."', army='".implode("-", $data[1][1])."', general='".implode("-", $data[1][2])."', rLoot='".implode("-", $data[3])."', wLoot='".implode("-", $data[4])."', intel='".implode("-", $data[5])."' where town=".$town[0]." and id=".$line[15];
				mysqli_query($db_id, $query);
				$data[0][1]=html_army($data[0][1], $ta_owner[10]); $data[1][1]=html_army($data[1][1], $to_owner[10]); $data[0][10]=html_army($data[0][10], $ta_owner[10]); $data[1][10]=html_army($data[1][10], $to_owner[10]); $data[3]=html_res($data[3]); $data[4]=html_weaps($data[4]);
				if ($siege_target>-1) $siege_target="</br>Demolished building: ".$buildings[$siege_target][2]; else $siege_target="";
				send_report($ta_owner[0], "Battle report, attacked", "attacked by <a class='q_link' href='profile_view.php?id=".$town[1]."'>".$town[2]."</a></br>enemy troops before battle:</br>".$data[1][10]."</br>and after:</br>".$data[1][1]."</br>your troops before battle:</br>".$data[0][10]."</br>and after:</br>".$data[0][1].$siege_target);
				send_report($to_owner[0], "Battle report, heroes homecoming", "returning from <a class='q_link' href='profile_view.php?id=".$target[1]."'>".$target[2]."</a></br>your troops before battle:</br>".$data[1][10]."</br>and after:</br>".$data[1][1]."</br>enemy troops before battle:</br>".$data[0][10]."</br>and after:</br>".$data[0][1]."</br> resources looted: ".$data[3]."</br> weapons looted: ".$data[4].$siege_target);
			}
			else if ($town[0])//if phase 1
			{
				$army=explode("-", $town[7]); for ($i=0; $i<13; $i++) $army[$i]+=$data[1][1][$i];
				$ogen=explode("-", $town[15]); if ($data[1][2][0]) {$data[1][2][3]=$ogen[3]; $ogen=$data[1][2];} $ogen=implode("-", $ogen);
				$res=explode("-", $town[10]); for ($i=0; $i<5; $i++) $res[$i]+=$data[3][$i]; $res=implode("-", $res);
				$weaps=explode("-", $town[6]); for ($i=0; $i<11; $i++) if ($weaps[$i]+$data[4][$i]<=$lim[12]) $weaps[$i]+=$data[4][$i]; else $weaps[$i]=$lim[12]; $weaps=implode("-", $weaps);
				$query="update towns set army='".implode("-", $army)."', upkeep=".array_sum($army).", general='".$ogen."', resources='".$res."', weapons='".$weaps."' where id=".$town[0];
				mysqli_query($db_id, $query);
				$query="delete from a_queue where town=".$town[0]." and id=".$line[15];
				mysqli_query($db_id, $query);
			}
		}
		else//reinforce target
		{
			$army=explode("-", $target[7]); $qarmy=explode("-", $line[5]); for ($i=0; $i<count($army); $i++) $army[$i]+=$qarmy[$i];
			$query="update towns set army='".implode("-", $army)."', upkeep=".array_sum($army)." where id=".$target[0];
			mysqli_query($db_id, $query);
			$query="delete from a_queue where town=".$town[0]." and id=".$line[15];
			mysqli_query($db_id, $query);
			$line[5]=html_army($qarmy, $to_owner[10]);
			send_report($to_owner[0], "Reinforcements sent", "</br>".$line[5]."</br>to <a class='q_link' href='profile_view.php?id=".$target[1]."'>".$target[2]."</a>");
			send_report($ta_owner[0], "Reinforcements received", "</br>".$line[5]."</br>troops arrived from <a class='q_link' href='profile_view.php?id=".$town[1]."'>".$town[2]."</a>");
		}
		else if ($town[0])//if source town exists
		{
			$army=explode("-", $town[7]); for ($i=0; $i<13; $i++) $army[$i]+=$data[1][1][$i];
			$ogen=explode("-", $town[15]); if ($data[1][2][0]) {$data[1][2][3]=$ogen[3]; $ogen=$data[1][2];} $ogen=implode("-", $ogen);
			$res=explode("-", $town[10]); for ($i=0; $i<5; $i++) $res[$i]+=$data[3][$i]; $res=implode("-", $res);
			$weaps=explode("-", $town[6]); for ($i=0; $i<11; $i++) if ($weaps[$i]+$data[4][$i]<=$lim[12]) $weaps[$i]+=$data[4][$i]; else $weaps[$i]=$lim[12]; $weaps=implode("-", $weaps);
			$query="update towns set army='".implode("-", $army)."', upkeep=".array_sum($army).", general='".$ogen."', resources='".$res."', weapons='".$weaps."' where id=".$town[0];
			mysqli_query($db_id, $query);
			$query="delete from a_queue where town=".$town[0]." and id=".$line[15];
			mysqli_query($db_id, $query);
		}
		else//if there is no target town and no source town
		{
			$query="delete from a_queue where town=".$town[0]." and id=".$line[15];
			mysqli_query($db_id, $query);
		}
	}
}

function check_u($id)
{
	global $db_id, $tdif;
	$town=town($id);
	$data=explode("-", $town[7]);

	$query="select timediff(dueTime".$tdif.", now()), type, quantity from u_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0][0]=="-")
	{
		$data[$row[1]]+=$row[2]; $d=implode("-", $data);
		$query="update towns set army='".$d."' where id=".$id;
		mysqli_query($db_id, $query);
		$query="delete from u_queue where town=".$id." and type=".$row[1];
		mysqli_query($db_id, $query);
	}
}

function check_uup($id)
{
	global $db_id, $tdif;
	$town=town($id);
	$data[17]=explode("-", $town[17]);
	$data[18]=explode("-", $town[18]);
	$data[19]=explode("-", $town[19]);
	$data[20]=explode("-", $town[20]);

	$query="select timediff(dueTime".$tdif.", now()), unit, tree from uup_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0][0]=="-")
	{
		$data[$row[2]][$row[1]]++; $d=implode("-", $data[$row[2]]);
		if ($row[2]==17)
		{
			$col="uUpgrades";
		}
		else if ($row[2]==18)
		{
			$col="wUpgrades";
		}
		else if ($row[2]==19)
		{
			$col="aUpgrades";
		}
		else if ($row[2]==20)
		{
			$col="sUpgrades";
		}

		$query="update towns set ".$col."='".$d."' where id=".$id;
		mysqli_query($db_id, $query);
		$query="delete from uup_queue where town=".$id." and unit=".$row[1]." and tree=".$row[2];
		mysqli_query($db_id, $query);
	}
}

function check_t($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), seller, buyer, sType, sSubType, sQ, bType, bSubType, bQ from t_queue where type=1 and (seller=".$id." or buyer=".$id.") order by dueTime asc";
	$result=mysqli_query($db_id, $query);

	for (; $offer=mysqli_fetch_row($result); )
	if ($offer[0][0]=="-")
	{
		$seller=town($offer[1]);
		$buyer=town($offer[2]);
		if ($offer[6]) {$scol="weapons"; $sdata=explode("-", $seller[6]);} else {$scol="resources"; $sdata=explode("-", $seller[10]);}
		if ($offer[3]) {$bcol="weapons"; $bdata=explode("-", $buyer[6]);} else {$bcol="resources"; $bdata=explode("-", $buyer[10]);}
		$sdata[$offer[7]]+=$offer[8]; $bdata[$offer[4]]+=$offer[5];
		$sdata=implode("-", $sdata); $bdata=implode("-", $bdata);
		$query="update towns set ".$scol."='".$sdata."' where id=".$seller[0];
		mysqli_query($db_id, $query);
		$query="update towns set ".$bcol."='".$bdata."' where id=".$buyer[0];
		mysqli_query($db_id, $query);
		$query="delete from t_queue where seller=".$offer[1]." and sType=".$offer[3]." and sSubType=".$offer[4]." and bType=".$offer[6]." and bSubType=".$offer[7];
		mysqli_query($db_id, $query);
	}
}

function check_d_all()
{
	global $db_id;

	$query="select timediff(dueTime, now()), user from d_queue";
	$result=mysqli_query($db_id, $query); $d_list=array(); $d=0;
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$d_list[$i]=$row;
		if ($row[0][0]=="-") if (!check_d($row[1])) $d++;
	}
	msg($d." users deleted. ".(count($d_list)-$d)." accounts not due.");
}

function get_d($id)
{
	global $db_id;

	$query="select timediff(dueTime, now()) from d_queue where user=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	return $row[0];
}

function get_con($id)
{
	global $db_id;

	$query="select b from c_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$b=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $b[$row[0]]=1;
	return $b;
}

function get_wea($id)
{
	global $db_id;

	$query="select type from w_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$w=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $w[$row[0]]=1;
	return $w;
}

function get_uup($id)
{
	global $db_id;

	$query="select unit from uup_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$u=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $u[$row[0]]=1;
	return $u;
}

function get_uns($id)
{
	global $db_id;

	$query="select type from u_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$u=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $u[$row[0]]=1;
	return $u;
}

function get_tr($id)
{
	global $db_id;

	$merchants=0;
	$query="select sType, sQ from t_queue where seller=".$id;
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0]) $merchants+=ceil($row[1]/50); else $merchants+=ceil($row[1]/500);
	$query="select bType, bQ from t_queue where buyer=".$id;
	$result=mysqli_query($db_id, $query);
	for (; $row=mysqli_fetch_row($result); )
	if ($row[0]) $merchants+=ceil($row[1]/50); else $merchants+=ceil($row[1]/500);

	return $merchants;
}

function get_t($id)
{
	global $db_id, $tdif;

	$tq=array();
	$query="select sType, sSubType, sQ, bType, bSubType, bQ from t_queue where seller=".$id." and type=0";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $tq[0][$i]=mysqli_fetch_row($result); $i++) ;
	$query="select bType, bSubType, bQ, buyer, timediff(dueTime".$tdif.", now()), sType, sSubType, sQ from t_queue where seller=".$id." and type=1";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $tq[1][$i]=mysqli_fetch_row($result); $i++) ;
	$query="select sType, sSubType, sQ, seller, timediff(dueTime".$tdif.", now()), bType, bSubType, bQ from t_queue where buyer=".$id." and type=1";
	$result=mysqli_query($db_id, $query);
	for ($i=0; $tq[2][$i]=mysqli_fetch_row($result); $i++) ;

	return $tq;
}

function get_w($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), type, quantity from w_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query); $wq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $wq[$i]=$row;
	return $wq;
}

function get_u($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), type, quantity from u_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query); $uq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $uq[$i]=$row;
	return $uq;
}

function get_a($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), target, type, army, general, id from a_queue where town=".$id." and phase=0 order by dueTime asc";
	$result=mysqli_query($db_id, $query); $aq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $aq[$i]=$row;
	return $aq;
}

function get_ia($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), town, target, type, phase from a_queue where (target=".$id." and phase=0) or (town=".$id." and phase=1) order by dueTime asc";
	$result=mysqli_query($db_id, $query); $iaq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $iaq[$i]=$row;
	return $iaq;
}

function get_up($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), unit, tree from uup_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query); $upq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $upq[$i]=$row;
	return $upq;
}

function get_c($id)
{
	global $db_id, $tdif;

	$query="select timediff(dueTime".$tdif.", now()), b, subB from c_queue where town=".$id." order by dueTime asc";
	$result=mysqli_query($db_id, $query); $cq=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $cq[$i]=$row;
	return $cq;
}

function get_pact($a1, $a2)
{
	global $db_id;

	$query="select type from pacts where (a1=".$a1." and a2=".$a2.") or (a1=".$a2." and a2=".$a1.")";
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	return $row[0];
}

function cancel_d($id)
{
	global $db_id;

	$query="delete from d_queue where user=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) msg("Delete request withdrawn.");
	else msg("Failed.".mysqli_error());
}

function cancel_c($id, $b, $subB, $res, $faction)
{
	global $db_id;
	$town=town($id);
	$buildings=buildings($faction);
	$data=explode("-", $town[8]); $land=explode("/", $town[13]); $upk=explode("-", $buildings[$b][7]);
	$land[0]=explode("-", $land[0]); $land[1]=explode("-", $land[1]); $land[2]=explode("-", $land[2]); $land[3]=explode("-", $land[3]);

	if ($subB==-1) $pop=$town[3]-$upk[$data[$b]];
	else $pop=$town[3]-$upk[$land[$b][$subB]];
	$query="update towns set resources='".$res."', population=".$pop." where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from c_queue where town=".$id." and b=".$b;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function cancel_a($id, $tid, $army, $gen)
{
	global $db_id;

	$army=explode("-", $army);
	$query="update towns set army='".implode("-", $army)."', upkeep=".array_sum($army).", general='".$gen."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from a_queue where town=".$id." and id=".$tid;
	$result=mysqli_query($db_id, $query);
	if ($result) header("Location: dispatch.php?town=".$id);
	else msg("Failed.".mysqli_error());
}

function cancel_w($id, $type, $res)
{
	global $db_id;

	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from w_queue where town=".$id." and type=".$type;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function cancel_u($id, $type, $res, $weaps, $q)
{
	global $db_id;
	$town=town($id); $town[7]=explode("-", $town[7]);

	$query="update towns set resources='".$res."', weapons='".$weaps."', upkeep=".array_sum($town[7])." where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from u_queue where town=".$id." and type=".$type;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function cancel_uup($id, $unit, $tree, $res)
{
	global $db_id;

	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from uup_queue where town=".$id." and unit=".$unit." and tree=".$tree;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function cancel_t($id, $sType, $sSubType, $bType, $bSubType, $res)
{
	global $db_id;
	$town=town($id);
	$data=explode("-", $town[6]);

	if ($sType) $scol="weapons"; else $scol="resources";
	$query="update towns set ".$scol."='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from t_queue where seller=".$id." and sType=".$sType." and sSubType=".$sSubType." and bType=".$bType." and bSubType=".$bSubType;
	$result=mysqli_query($db_id, $query);
	if ($result) header("Location: marketplace.php?town=".$id);
	else msg("Failed.".mysqli_error());
}

function send_report($to, $subject, $contents)
{
	global $db_id;

	$query="insert into reports(recipient, subject, contents, sent) values(".$to.", '".mysqli_real_escape_string($subject)."', '".mysqli_real_escape_string($contents)."', now())";
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function send_to_all($subject, $contents)
{
	global $db_id;

	$users=users();
	for ($i=0; $i<count($users); $i++)
	{
		$query="insert into reports(recipient, subject, contents, sent) values(".$users[$i][0].", '".$subject."', '".$contents."', now())";
		mysqli_query($db_id, $query);
	}
}

function send_message($from, $to, $subject, $contents)
{
	global $db_id;

	$query="insert into messages(sender, recipient, subject, contents, sent) values(".$from.", ".$to.", '".$subject."', '".$contents."', now())";
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function msg_rep_alert($id)
{
	global $db_id;

	$output=array();
	$query="select count(*) from reports where recipient=".$id." and timediff('".$_SESSION["user"][6]."', sent)<'00:00:00'";
	$result=mysqli_query($db_id, $query); $output[0]=mysqli_fetch_row($result);
	$query="select count(*) from messages where recipient=".$id." and timediff('".$_SESSION["user"][6]."', sent)<'00:00:00'";
	$result=mysqli_query($db_id, $query); $output[1]=mysqli_fetch_row($result);
	return $output;
}

function messages($id)
{
	global $db_id;

	$query="select * from messages where recipient=".$id." order by sent desc";
	$result=mysqli_query($db_id, $query); $reports=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$reports[$i]=$row;
		if (strtotime($row[5])>strtotime($_SESSION["user"][6])) $reports[$i][6]=1; else $reports[$i][6]=0;//if message is new
	}
	return $reports;
}

function reports($id)
{
	global $db_id;

	$query="select * from reports where recipient=".$id." order by sent desc";
	$result=mysqli_query($db_id, $query); $reports=array();
	for ($i=0; $row=mysqli_fetch_row($result); $i++)
	{
		$reports[$i]=$row;
		if (strtotime($row[4])<strtotime($_SESSION["user"][4])) $reports[$i][5]=1; else $reports[$i][5]=0;//if report is new
	}
	return $reports;
}

function offers($sType, $sSubType, $bType, $bSubType)
{
	global $db_id;

	$offers=array();
	$query="select * from t_queue where type=0 and sType=".$sType." and sSubType=".$sSubType." and bType=".$bType." and bSubType=".$bSubType;
	$result=mysqli_query($db_id, $query);
	for ($i=0; $row=mysqli_fetch_row($result); $i++) $offers[$i]=$row;
	return $offers;
}

function offer($seller, $sType, $sSubType, $bType, $bSubType)
{
	global $db_id;

	$query="select * from t_queue where seller=".$seller." and sType=".$sType." and sSubType=".$sSubType." and bType=".$bType." and bSubType=".$bSubType;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	return $row;
}

function report($id)
{
	global $db_id;

	$query="select * from reports where id=".$id;
	$result=mysqli_query($db_id, $query);
	$reports=array();
	$reports=mysqli_fetch_row($result);
	return $reports;
}

function message($id)
{
	global $db_id;

	$query="select * from messages where id=".$id;
	$result=mysqli_query($db_id, $query);
	$reports=array();
	$reports=mysqli_fetch_row($result);
	return $reports;
}

function delrep($id, $owner)
{
	global $db_id;
	$report=report($id);

	if ($owner!=$report[1]) { msg($lang['accessDenied']);}
	else
	{
		$query="delete from reports where id=".$id;
		$result=mysqli_query($db_id, $query); $reports=array();
		if ($result) header('Location: reports.php?page=0');
		else msg("Failed.".mysqli_error());
	}
}

function delallrep($id)
{
	global $db_id;

	$query="delete from reports where recipient=".$id;
	$result=mysqli_query($db_id, $query); $reports=array();
	if ($result) header('Location: reports.php?page=0');
	else msg("Failed.".mysqli_error());
}

function delmsg($id, $owner)
{
	global $db_id;
	$message=message($id);

	if ($owner!=$message[2]) { msg($lang['accessDenied']);}
	else
	{
		$query="delete from messages where id=".$id;
		$result=mysqli_query($db_id, $query); $reports=array();
		if ($result) header('Location: messages.php?page=0');
		else msg("Failed.".mysqli_error());
	}
}

function delallmsg($id)
{
	global $db_id;

	$query="delete from messages where recipient=".$id;
	$result=mysqli_query($db_id, $query); $reports=array();
	if ($result) header('Location: messages.php?page=0');
	else msg("Failed.".mysqli_error());
}

function delacc($id)
{
	global $db_id;

	$query="select count(*) from d_queue where user=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if (!$row[0])
	{
		$date=strtotime("+1 day"); $date=strftime("%Y-%m-%d %H:%M:%S", $date);
		$query="insert into d_queue(user, dueTime) values('".$id."', '".$date."')";
		$result=mysqli_query($db_id, $query);
		if ($result) msg("Account will be deleted in 24 hours.");
		else msg("Failed.".mysqli_error());
	} else msg("Account is already scheduled for deletion.");
}

function build($id, $b, $subB, $time, $res, $faction)
{
	global $db_id;
	$town=town($id); $buildings=buildings($faction); $data=explode("-", $town[8]); $land=explode("/", $town[13]); $upk=explode("-", $buildings[$b][7]);
	$land[0]=explode("-", $land[0]); $land[1]=explode("-", $land[1]); $land[2]=explode("-", $land[2]); $land[3]=explode("-", $land[3]);

	$time=explode(":", $time);

	$query="select max(dueTime) from c_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0]!="") $date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".($time[2]+rand(0, 9))." seconds", strtotime($row[0])); else $date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".($time[2]+rand(0, 9))." seconds");
	$date=strftime("%Y-%m-%d %H:%M:%S", $date);
	$query="insert into c_queue(town, dueTime, b, subB) values('".$id."', '".$date."', '".$b."', '".$subB."')";
	$result=mysqli_query($db_id, $query);
	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($subB==-1) $pop=$town[3]+$upk[$data[$b]];
	else $pop=$town[3]+$upk[$land[$b][$subB]];
	$query="update towns set population=".$pop." where id=".$id;
	$result=mysqli_query($db_id, $query);

	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function forge($a, $id, $type, $q, $time, $res)
{
	global $db_id;
	$town=town($id);

	$time=explode(":", $time);

	if (!$a) $query="select max(dueTime) from w_queue where town=".$id;
	else $query="select dueTime from w_queue where town=".$id." and type=".$type;
	$query="select dueTime from w_queue where town=".$id." and type=".$type;
	$result=mysqli_query($db_id, $query); $row=mysqli_fetch_row($result);
	if ($row[0]!="")
	{
		$date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".$time[2]." seconds", strtotime($row[0]));
	}
	else
	{
		$date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".$time[2]." seconds");
	}
	// reset time so faster build
	//$date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".$time[2]." seconds");
	$date=strftime("%Y-%m-%d %H:%M:%S", $date);
	if (!$a) $query="insert into w_queue(town, dueTime, type, quantity) values('".$id."', '".$date."', '".$type."', '".$q."')";
	else $query="update w_queue set dueTime='".$date."', quantity=quantity+".$q." where town=".$id." and type=".$type;
	$result=mysqli_query($db_id, $query);
	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function train($a, $id, $type, $q, $time, $res, $weaps)
{
	global $db_id;
	$town=town($id); $town[7]=explode("-", $town[7]);

	$time=explode(":", $time);

	if (!$a) $query="select max(dueTime) from u_queue where town=".$id;
	else $query="select dueTime from u_queue where town=".$id." and type=".$type;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0]!="") $date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".$time[2]." seconds", strtotime($row[0])); else $date=strtotime("+".$time[0]." hours ".$time[1]." minutes ".$time[2]." seconds");
	$date=strftime("%Y-%m-%d %H:%M:%S", $date);
	if (!$a)
	{
		$query="insert into u_queue(town, dueTime, type, quantity) values('".$id."', '".$date."', '".$type."', '".$q."')";
	}
	else
	{
		$query="update u_queue set dueTime='".$date."', quantity=quantity+".$q." where town=".$id." and type=".$type;
	}
	$result=mysqli_query($db_id, $query);
	$query="update towns set resources='".$res."', 
	weapons='".$weaps."', 
	upkeep=".(array_sum($town[7])+$q)." 
	where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) echo "<script type='text/javascript'>history.go(-1)</script>";
	else msg("Failed.".mysqli_error());
}

function set_gen($id, $utype)
{
	global $db_id;
	$town=town($id);

	$query="update towns set general='1-1-".$utype."-0' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) msg("Unit promoted to general. You can only have one general. Promoting another unit will demote the current general.");
	else msg("Failed.".mysqli_error());
}

function battle($data)
{
	$d_units=units($data[0][0]);
	$a_units=units($data[1][0]);
	$def=array(); $atk=array(); $data[0][10]=$data[0][1]; $data[1][10]=$data[1][1];
	$bo[0][1]=$data[0][4][6]; $bo[0][0]=$data[0][4][7]; $bo[1][1]=0; $bo[1][0]=0;//def&atk bonuses
	switch($data[0][2][3])
	{
		case 1: $bo[0][0]+=0.25*$bo[0][0]; $bo[0][1]-=0.25*$bo[0][1]; break;//offensive
		case 2: $bo[0][0]-=0.25*$bo[0][0]; $bo[0][1]+=0.25*$bo[0][1]; break;//defensive
	}
	switch($data[1][2][3])
	{
		case 1: $bo[1][0]+=0.25*$bo[1][0]; $bo[1][1]-=0.25*$bo[1][1]; break;//offensive
		case 2: $bo[1][0]-=0.25*$bo[1][0]; $bo[1][1]+=0.25*$bo[1][1]; break;//defensive
	}
	//naval combat
	if ((($data[1][1][9])||($data[1][1][10]))&&(($data[0][1][9])||($data[0][1][10])))
	{
		$def[0]=($d_units[9][5]+$data[0][7][9])*$data[0][1][9]+($d_units[10][5]+$data[0][7][10])*$data[0][1][10]; $def[1]=($d_units[9][6]+$data[0][8][9])*$data[0][1][9]+($d_units[10][6]+$data[0][8][10])*$data[0][1][10]; $def[2]=($d_units[9][7]+$data[0][9][9]+$d_units[10][7]+$data[0][9][10])/2;
		$def[1]+=$def[1]*$bo[0][0]/100; $def[2]+=$def[2]*$bo[0][1]/100;
		$atk[0]=($a_units[9][5]+$data[1][3][9])*$data[1][1][9]+($a_units[10][5]+$data[1][3][10])*$data[1][1][10]; $atk[1]=($a_units[9][6]+$data[1][4][9])*$data[1][1][9]+($a_units[10][6]+$data[1][4][10])*$data[1][1][10]; $atk[2]=($a_units[9][7]+$data[1][5][9]+$a_units[10][7]+$data[1][5][10])/2;
		$atk[1]+=$atk[1]*$bo[1][0]/100; $atk[2]+=$atk[2]*$bo[1][1]/100;
		$ah=$def[0]/$atk[1]*(100-$def[2])/100; $dh=$atk[0]/$def[1]*(100-$atk[2])/100;
		$admg=($atk[0]-$ah*$def[1]*(100-$atk[2])/100)/$atk[0]; $ddmg=($def[0]-$dh*$atk[1]*(100-$def[2])/100)/$def[0];
		if ($admg<0) $admg=0; else if ($admg>1) $admg=1;
		if ($ddmg<0) $ddmg=0; else if ($ddmg>1) $ddmg=1;
		if ($ah<$dh)//if attacking ships win
		{
			$data[1][1][9]=ceil($data[1][1][9]*$admg); $data[1][1][10]=ceil($data[1][1][10]*$admg);
			$data[0][1][9]=0; $data[0][1][10]=0;
			for ($i=0; $i<count($a_units); $i++) if (($i<9)||($i>10)) $data[1][1][$i]=ceil($data[1][1][$i]*$admg);//drowned units
		}
		else//if defending ships win
		{
			$data[0][1][9]=ceil($data[0][1][9]*$ddmg); $data[0][1][10]=ceil($data[0][1][10]*$ddmg);
			$data[1][1]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			$data[0][2][1]++; if ($data[1][2][1]) $data[1][2][1]--;//defending general promoted, the other demoted
			$data[3]=array(0, 0, 0, 0, 0); $data[4]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			return $data;
		}
	}
	//land combat
	$def[0]=0; $def[1]=0; $def[2]=0; $atk[0]=0; $atk[1]=0; $atk[2]=0;
	for ($i=0; $i<count($d_units); $i++) if (($i<9)||($i>10))
	{
		$def[0]+=($d_units[$i][5]+$data[0][7][$i])*$data[0][1][$i]; $def[1]+=($d_units[$i][6]+$data[0][8][$i])*$data[0][1][$i]; $def[2]+=$d_units[$i][7]+$data[0][9][$i];
		$atk[0]+=($a_units[$i][5]+$data[1][3][$i])*$data[1][1][$i]; $atk[1]+=($a_units[$i][6]+$data[1][4][$i])*$data[1][1][$i]; $atk[2]+=$a_units[$i][7]+$data[1][5][$i];
	}
	if ($data[0][2][0]) {$def[1]+=($d_units[$data[0][2][2]][6]+$data[0][8][$data[0][2][2]])*$data[0][2][1]; $def[2]+=$d_units[$data[0][2][2]][7]+$data[0][9][$data[0][2][2]];}
	if ($data[1][2][0]) {$atk[1]+=($a_units[$data[1][2][2]][6]+$data[1][4][$data[1][2][2]])*$data[1][2][1]; $atk[2]+=$a_units[$data[1][2][2]][7]+$data[1][5][$data[1][2][2]];}
	$def[2]/=11; $def[1]+=$def[1]*$bo[0][0]/100; $def[2]+=$def[2]*$bo[0][1]/100;
	$atk[2]/=11; $atk[1]+=$atk[1]*$bo[1][0]/100; $atk[2]+=$atk[2]*$bo[1][1]/100;
	/*
	 $atk - attacker data
	 $def - defender data
	 ---
	 0 - hp, 1 - atk, 2 - def
	 */
	if (($atk[0])&&($def[0]))//if any attaking/defending troops remained
	{
		$ah=$def[0]/$atk[1]*(100-$def[2])/100; $dh=$atk[0]/$def[1]*(100-$atk[2])/100;
		$admg=($atk[0]-$ah*$def[1]*(100-$atk[2])/100)/$atk[0]; $ddmg=($def[0]-$dh*$atk[1]*(100-$def[2])/100)/$def[0];
		$qadmg=($atk[0]-$def[1]*(100-$atk[2])/100)/$atk[0]; $qddmg=($def[0]-$atk[1]*(100-$def[2])/100)/$def[0];
		if ($admg<0) $admg=0; else if ($admg>1) $admg=1;
		if ($ddmg<0) $ddmg=0; else if ($ddmg>1) $ddmg=1;
		if ($qadmg<0) $qadmg=0; else if ($qadmg>1) $qadmg=1;
		if ($qddmg<0) $qddmg=0; else if ($qddmg>1) $qddmg=1;
		if ($ah<$dh)//if attackers win
		{
			if ($data[2]==2)//if there was an 'attack'
			{
				$atc=0;
				for ($i=0; $i<count($d_units); $i++) {$data[1][1][$i]=ceil($data[1][1][$i]*$admg); $atc+=$data[1][1][$i];}
				$data[0][1]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
				//siege damage
				if (($data[1][1][7])||($data[1][1][8])) {$b=rand(0, 21); if ($data[0][3][$b]) $data[0][3][$b]--;}
				//plunder
				$atc*=10;//each unit can carry 10 of each resource
				for ($i=0; $i<5; $i++)
				if ($atc>0)
				{
					if ($data[0][5][$i]-$data[0][4][5]>$atc) {$data[3][$i]=$atc; $data[0][5][$i]-=$atc;} else if ($data[0][5][$i]-$data[0][4][5]>0) {$data[3][$i]=$data[0][5][$i]-$data[0][4][5]; $data[0][5][$i]=$data[0][4][5];} else $data[3][$i]=0;
				} else $data[3][$i]=0;
				$atc/=10;//each unit can carry 1 of each weapon
				for ($i=0; $i<11; $i++)
				if ($atc>0)
				{
					if ($data[0][6][$i]>$atc) {$data[4][$i]=$atc; $data[0][6][$i]-=$atc;} else {$data[4][$i]=$data[0][6][$i]; $data[0][6][$i]=0;}
				} else $data[4][$i]=0;
				$data[1][2][1]++; if ($data[0][2][1]) $data[0][2][1]--;//attacking general promoted, the other demoted
			}
			else//if there was a 'raid' or 'spy' mission
			{
				$atc=0;
				for ($i=0; $i<count($d_units); $i++)
				{
					$data[1][1][$i]=ceil($data[1][1][$i]*$qadmg); $data[0][1][$i]=ceil($data[0][1][$i]*$qddmg); $atc+=$data[1][1][$i];
					//check to see if one side >> the other
					if ($data[1][1][$i]<=0) $data[1][1][$i]=0; if ($data[0][1][$i]<=0) $data[0][1][$i]=0;
				}
				$atc*=10;//each unit can carry 10 of each resource
				for ($i=0; $i<5; $i++)
				if ($atc>0)
				{
					if ($data[0][5][$i]-$data[0][4][5]>$atc) {$data[3][$i]=$atc; $data[0][5][$i]-=$atc;} else if ($data[0][5][$i]-$data[0][4][5]>0) {$data[3][$i]=$data[0][5][$i]-$data[0][4][5]; $data[0][5][$i]=$data[0][4][5];} else $data[3][$i]=0;
				} else $data[3][$i]=0;
				$atc/=10;//each unit can carry 1 of each weapon
				for ($i=0; $i<11; $i++)
				if ($atc>0)
				{
					if ($data[0][6][$i]>$atc) {$data[4][$i]=$atc; $data[0][6][$i]-=$atc;} else {$data[4][$i]=$data[0][6][$i]; $data[0][6][$i]=0;}
				} else $data[4][$i]=0;
				if ($data[2]==3) $data[5]=$data[0][1];
			}
		}
		else//if defenders win
		{
			if ($data[2]==2)//if there was an 'attack'
			{
				for ($i=0; $i<count($a_units); $i++) $data[0][1][$i]=ceil($data[0][1][$i]*$ddmg);
				$data[1][1]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
				$data[0][2][1]++; if ($data[1][2][1]) $data[1][2][1]--;//defending general promoted, the other demoted
				$data[3]=array(0, 0, 0, 0, 0); $data[4]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			}
			else//if there was a 'raid' or 'spy' mission
			for ($i=0; $i<count($a_units); $i++)
			{
				$data[0][1][$i]=ceil($data[0][1][$i]*$qddmg); $data[1][1][$i]=ceil($data[1][1][$i]*$qadmg);
				//check to see if one side >> the other
				if ($data[0][1][$i]<=0) $data[0][1][$i]=0; if ($data[1][1][$i]<=0) $data[1][1][$i]=0;
			}
			$data[3]=array(0, 0, 0, 0, 0); $data[4]=array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
		}
	}
	else if ($atk[0])//if there are no defenders
	{
		//if attack, siege damage
		if ($data[2]==2) if (($data[1][1][7])||($data[1][1][8])) {$b=rand(0, 21); if ($data[0][3][$b]) $data[0][3][$b]--;}
		$atc=0; for ($i=0; $i<count($d_units); $i++) $atc+=$data[1][1][$i];
		$atc*=10;//each unit can carry 10 of each resource
		for ($i=0; $i<5; $i++) if ($data[0][5][$i]-$data[0][4][5]>$atc) {$data[3][$i]=$atc; $data[0][5][$i]-=$atc;} else if ($data[0][5][$i]-$data[0][4][5]>0) {$data[3][$i]=$data[0][5][$i]-$data[0][4][5]; $data[0][5][$i]=$data[0][4][5];} else $data[3][$i]=0;
		$atc/=10;//each unit can carry 1 of each weapon
		for ($i=0; $i<11; $i++) if ($data[0][6][$i]>$atc) {$data[4][$i]=$atc; $data[0][6][$i]-=$atc;} else {$data[4][$i]=$data[0][6][$i]; $data[0][6][$i]=0;}
		$data[5]=$data[0][1];
	}
	return $data;
}

function trade($id, $buyer, $sQ, $sType, $sSubType, $bQ, $bType, $bSubType, $type, $dueTime, $res, $maxTime)
{
	global $db_id;
	$town=town($id);
	$loc=town_xy($id);
	if ($sType) $scol="weapons"; else $scol="resources";

	$query="select count(*) from t_queue where seller=".$id." and sType=".$sType." and sSubType=".$sSubType." and bType=".$bType." and bSubType=".$bSubType;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if (!$row[0])
	{
		$query="insert into t_queue(seller, buyer, sType, sSubType, sQ, bType, bSubType, bQ, type, dueTime, x, y, water, maxTime) values(".$id.", ".$buyer.", ".$sType.", ".$sSubType.", ".$sQ.", ".$bType.", ".$bSubType.", ".$bQ.", ".$type.", '".$dueTime."', ".$loc[0].", ".$loc[1].", ".$town[16].", ".$maxTime.")";
		mysqli_query($db_id, $query);
		$query="update towns set ".$scol."='".$res."' where id=".$id;
		$result=mysqli_query($db_id, $query);
		if ($result) header("Location: marketplace.php?town=".$id);
		else msg("Failed.".mysqli_error());
	} else { msg("You already have an offer/transport of same type underway.");}
}

function npc_trade($id, $res)
{
	global $db_id;

	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1; else return 0;
}

function upgrade_u($id, $res, $unit, $tree, $time)
{
	global $db_id;

	$time=explode(":", $time);
	$query="select max(dueTime) from uup_queue where town=".$id;
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0]!="")
	{
		$date=strtotime("+ ".$time[0]." hours ".$time[1]." minutes", strtotime($row[0]));
	}
	else
	{
		$date=strtotime("+ ".$time[0]." hours ".$time[1]." minutes");
	}
	$date=strftime("%Y-%m-%d %H:%M:%S", $date);
	$query="insert into uup_queue(town, unit, tree, dueTime) values(".$id.", ".$unit.", ".$tree.", '".$date."')";
	mysqli_query($db_id, $query);
	$query="update towns set resources='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if (!$result)
	{
		msg("Failed.".mysqli_error());
	}
} // end fx

function dispatch($town, $target, $type, $dueTime, $time, $qarmy, $army, $gen)
{
	global $db_id;

	$query="select max(id), count(*) from a_queue where town=".$town[0];
	$result=mysqli_query($db_id, $query);
	$id=mysqli_fetch_row($result);
	if ($id[1]) $id=$id[0]+1; else $id=1;
	$query="insert into a_queue(town, target, id, type, phase, dueTime, army, general, uup, wup, aup, sent) values(".$town[0].", ".$target[0].", ".$id.", ".$type.", 0, '".$dueTime."', '".$qarmy."', '".$gen."', '".$town[17]."', '".$town[18]."', '".$town[19]."', '".$time."')";
	mysqli_query($db_id, $query); $army=explode("-", $army);
	$ogen=explode("-", $town[15]); $gen=explode("-", $gen); if (($gen[0])&&($type)) $ogen[0]=0; $ogen=implode("-", $ogen);
	$query="update towns set army='".implode("-", $army)."', general='".$ogen."', upkeep=".array_sum($army)." where id=".$town[0];
	$result=mysqli_query($db_id, $query);
	if (!$result) msg("Failed.".mysqli_error());
}

function pass($id, $pass)
{
	global $db_id;

	$query="update users set pass='".$pass."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) msg("Succes. Password changed.");
	else msg("Failure.".mysqli_error());
}

function ban($name, $value)
{
	global $db_id;

	$query="update users set level='".$value."' where name='".$name."'";
	$result=mysqli_query($db_id, $query);
	if ($result)
	if ($value) msg("Succes. User '".$name."' level changed.");
	else msg("Succes. User '".$name."' level changed.");
	else msg("Failure.".mysqli_error());
}

function ch_capital($name, $usr_id)
{
	global $db_id;

	$usr=user($usr_id); $town=town_($name);
	if ($town[1]==$usr_id)
	if($town[0])
	{
		$query="select id from towns where isCapital=1 and owner=".$usr[0];
		$result=mysqli_query($db_id, $query); $row=mysqli_fetch_row($result);
		$query="update towns set isCapital=0 where id=".$row[0];
		mysqli_query($db_id, $query);
		$query="update towns set isCapital=1 where id=".$town[0];
		$result=mysqli_query($db_id, $query);
		if ($result) msg("Succes. The town '".$town[2]."' is now your capital.");
		else msg("Failed.".mysqli_error());
	}
	else msg("Did not succeed.");
	else msg("You are not the owner of this town.");
}

function ch_lang($id, $lang)
{
	global $db_id;

	$query="update users set lang='".$lang."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function profile($id, $email, $desc, $sitter, $grpath, $lang)
{
	global $db_id;

	$query="update users set email='".$email."', description='".$desc."', sitter='".$sitter."', grPath='".$grpath."', lang='".$lang."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) msg("Succes. Profile changed.");
	else msg("Failure.".mysqli_error());
}

function reg($name, $pass, $email, $faction)
{
	global $db_id;

	$query="insert into users(name, pass, email, level, joined, lastVisit, points, ip, grPath, faction) values('".$name."', '".$pass."', '".$email."', 1, now(), now(), 0, '".$_SERVER["REMOTE_ADDR"]."', 'default/', ".$faction.")";
	$result=mysqli_query($db_id, $query);
	if ($result) msg("Succes. You are now registered as '".$name."'. You can now login and create your town.");
	else msg("Failed.".mysqli_error());
}

function a_create($name, $founder)
{
	global $db_id;

	$query="select count(*) from alliances where name='".$name."'";
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0]) { msg("Name taken.");}
	else
	{
		$query="insert into alliances(name, founder) values('".$name."', ".$founder.")";
		$result=mysqli_query($db_id, $query);
		$query="select LAST_INSERT_ID()";
		$result=mysqli_query($db_id, $query);
		$row=mysqli_fetch_row($result);
		$query="update users set alliance=".$row[0].", rank='founder' where id=".$founder;
		$result=mysqli_query($db_id, $query);
		if ($result) return $row[0];
		else msg("Failed.".mysqli_error());
	}
}

function a_join($a_id, $usr_id)
{
	global $db_id;

	$query="select count(*) from reports where recipient=".$usr_id." and subject='Invitation/".$a_id."'";
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if ($row[0])
	{
		$query="delete from reports where recipient=".$usr_id." and subject='Invitation/".$a_id."'";
		mysqli_query($db_id, $query);
		$query="update users set alliance=".$a_id.", rank='member' where id=".$usr_id;
		$result=mysqli_query($db_id, $query);
		if ($result) return 1;
	}
	else { return 0;}
}

function a_quit($id)
{
	global $db_id;

	$query="update users set alliance=0 where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function a_del($id)
{
	global $db_id;

	$query="delete from alliances where id=".$id;
	$result=mysqli_query($db_id, $query);
	$query="delete from pacts where a1=".$id." or a2=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function pact($type, $name, $id)
{
	global $db_id;
	$a2=alliance_($name);
	$a1=alliance($id);
	$usr=user($a1[2]);

	if (!$type)
	{
		if (send_report($a2[2], "Peace pact/".$a1[0]."-".$a2[0], "You have been invited to make peace with the <a class='q_link' href='a_view.php?id=".$a1[0]."'>".$a1[1]."</a> alliance, founded by <a class='q_link' href='profile_view.php?id=".$a1[2]."'>".$usr[1]."</a>.</br></br>[ <a class='q_link' href='peace_.php?a1=".$a1[0]."&a2=".$a2[0]."'>accept</a> ]")) return 1;
		else return 0;
	}
	else
	{
		$query="delete from pacts where type=0 and ((a1=".$a1[0]." and a2=".$a2[0].") or ((a1=".$a2[0]." and a2=".$a1[0].")))";
		mysqli_query($db_id, $query);
		$query="insert into pacts(type, a1, a2) values(1, ".$a1[0].", ".$a2[0].")";
		$result=mysqli_query($db_id, $query);
		if ($result) return 1;
		else return 0;
	}
	return 0;
}

function peace_($a1, $a2)
{
	global $db_id;
	$a1=alliance($a1);
	$a2=alliance($a2);

	$query="select count(*) from reports where recipient=".$a2[2]." and subject='Peace pact/".$a1[0]."-".$a2[0]."'";
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	if (!$row[0]) { return 0;}
	$query="delete from pacts where type=1 and ((a1=".$a2[0]." and a2=".$a1[0].") or ((a1=".$a1[0]." and a2=".$a2[0].")))";
	mysqli_query($db_id, $query);
	$query="delete from reports where recipient=".$a2[2]." and subject='Peace pact/".$a1[0]."-".$a2[0]."'";
	mysqli_query($db_id, $query);
	$query="insert into pacts(type, a1, a2) values(0, ".$a1[0].", ".$a2[0].")";
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function dis_peace($a1, $a2)
{
	global $db_id;

	$query="delete from pacts where a1=".$a1." and a2=".$a2;
	$result=mysqli_query($db_id, $query);
	if ($result) return 1;
	else return 0;
}

function o_accept($id, $seller, $sType, $sSubType, $bType, $bSubType, $res, $dueTime)
{
	global $db_id;

	if ($bType) $bcol="weapons"; else $bcol="resources";
	$query="update t_queue set type=1, buyer=".$id.", dueTime='".$dueTime."' where seller=".$seller." and sType=".$sType." and sSubType=".$sSubType." and bType=".$bType." and bSubType=".$bSubType;
	$result=mysqli_query($db_id, $query);
	$query="update towns set ".$bcol."='".$res."' where id=".$id;
	$result=mysqli_query($db_id, $query);
	if ($result) header("Location: marketplace.php?town=".$id);
	else msg("Failed.".mysqli_error());
}

function create($owner, $name, $x, $y, $is_cap)
{
	global $db_id;

	$query="select count(*) from towns where x=".$x." and y=".$y.";";
	$notavail=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($notavail);
//	d($row);
//	die();
	if ($row[0] > 0) 
		{	
		msg("Too late, land plot was taken, there is something there.");
		die();
		}	
	$query="select name from map where x=".$x." and y=".$y.";";
	$result=mysqli_query($db_id, $query);
	$row=mysqli_fetch_row($result);
	//$name = ;
			switch($is_cap)
			{
				// map depends on this db data
				// 2 - housing
				// 3 - farm/grain mill
				// 4 - lumber
				// 5 - mine
				// 6 - farmcow600-400-200-20-100
				case 1: $land="0-0-0-0-0-0/0/0/0"; $name = $row[0] . " Capital City"; $res = "600-400-400-400-200";break; // capital
				case 2: $land="0/0/0/0"; $name = $row[0] . " Housing Estate"; $res = "0-0-0-0-0";break;
				case 3: $land="0/0/0/0"; $name = $row[0] . " Farm Valley"; $res = "0-0-0-0-0";break;
				case 4: $land="0/0/0/0"; $name = $row[0] . " Lumber Hills"; $res = "0-0-0-0-0";break;
				case 5: $land="0/0/0/0"; $name = $row[0] . " Stone Peak"; $res = "0-0-0-0-0";break;
				case 6: $land="0/0/0/0"; $name = $row[0] . " Mining Town"; $res = "0-0-0-0-0";break;
				default: $land="0-0-0-0-0-0/0/0/0"; $res = "0-0-0-0-0";break; // unknown
			}
		$query="select subtype from map where ((x=".$x." and y=".($y-1).") or (x=".($x-1)." and y=".$y.") or (x=".$x." and y=".($y+1).") or (x=".($x+1)." and y=".$y.")) and type=0";
		$result=mysqli_query($db_id, $query);
		$index=-1;
		while ($row=mysqli_fetch_row($result))
		{ 
			if ($row[0]>-1) 
				{
					$index=$row[0];
				}
		}

		$query="insert into towns(owner, name, population, isCapital, morale, weapons, army, 						buildings, 													production, 			resources, limits, 											upkeep, land, general, water, uUpgrades, wUpgrades, aUpgrades, lastCheck, x, y)
		values(".$owner.", '".$name."', 1, ".$is_cap.", 100, '0-0-0-0-0-0-0-0-0-0-0', '0-0-0-0-0-0-0-0-0-0-0-0-0', '0-0-0-0-0-0-0-1-0-0-0-0-0-0-0-0-0-0-0-0-0-0', '120-60-60-60-0', '".$res."', '600-400-200-20-100-0-0-0-0-0-0-0-0', 0, '".$land."', '0-0-0-0', ".$index.", '0-0-0-0-0-0-0-0-0-0-0-0-0', '0-0-0-0-0-0-0-0-0-0-0-0-0', '0-0-0-0-0-0-0-0-0-0-0-0-0', now(),
		".$x.", ".$y.");";
		//d($query);die();
		mysqli_query($db_id, $query);
		$query="select LAST_INSERT_ID()";
		$result=mysqli_query($db_id, $query);
		$row=mysqli_fetch_row($result);


		//$query="update map set type=".$is_cap.", subtype=".$row[0]." where x=".$x." and y=".$y;
		$query="update map set used_as=".$is_cap.", owner=".$owner.", townsid=".$row[0]." where x=".$x." and y=".$y;
		mysqli_query($db_id, $query);
		if (!$is_cap)
		{
			
			$towns=towns($_SESSION["user"][0]);
			$army=explode("-", $towns[0][7]); $army[11]-=100; $army=implode("-", $army);
			$query="update towns set army='".$army."', upkeep=upkeep-100 where id=".$towns[0][0];
			mysqli_query($db_id, $query);
		}
		if ($result)
			{
				msg("Success. Your town/village has been created. Read the beginner's guide found in the help section.");
			}
		else 
			{
				msg("Failed.".mysqli_error());
			}
}

function install($name, $pass, $email, $faction)
{
	global $db_id;

	$query="insert into users(name, pass, email, level, joined, lastVisit, points, ip, grPath, faction) values('".$name."', '".$pass."', '".$email."', 5, now(), now(), 0, '".$_SERVER["REMOTE_ADDR"]."', 'default/', ".$faction.")";
	$result=mysqli_query($db_id, $query);

	$handle = fopen ("map.dat","r") or
	die("Error opening map data file."); $ok=1;
	for ($i=0; $info[$i] = fscanf ($handle, "%i %i %i %i"); $i++)
	{
		if (!$info[$i][3])
		switch($info[$i][2])
		{
			case 1: $info[$i][3]=rand(1, 6); break;
			case 2: $info[$i][3]=rand(1, 4); break;
			default: ;
		}
		$query="insert into map(x, y, type, subtype) values (".$info[$i][0] .", ".$info[$i][1].", ".$info[$i][2].", ".$info[$i][3].")";
		$result=mysqli_query($db_id, $query);	if (!$result) $ok=0;
	}
	fclose($handle);
	if ($ok) msg(" Succes. Map data added.");
	else msg("Failed.".mysqli_error());
}
//chat functions
function send_chat($se, $sid, $msg, $re)
{
	global $db_id;

	$query="insert into chat (sId, timeStamp, message, recipient, sender) values (".$sid.", now(), '".$msg."', ".$re.", ".$se.")";
	mysqli_query($db_id, $query);
}

function mute($id, $v)
{
	global $db_id;

	$query="update users set mute=".$v." where id=".$id;
	mysqli_query($db_id, $query);
}

function get_chat($id, $sid, $lcheck, $span)
{
	global $db_id, $tdif;

	$query="delete from chat where hour(timediff(now(), timeStamp))>".($span/60)." or minute(timediff(now(), timeStamp))>".($span%60);
	$result=mysqli_query($db_id, $query);
	$query="select message from chat where (sId=".$sid." and timeStamp>'".$lcheck."'".$tdif." and ((recipient=0 or recipient=".$id.") or sender=".$id.")) or (timeStamp>'".$lcheck."'".$tdif." and recipient=".$id.")";
	$result=mysqli_query($db_id, $query);
	$msgs=array(); for ($i=0; $row=mysqli_fetch_row($result); $i++) $msgs[$i]=$row[0];
	return $msgs;
}

function chat_s()
{
	global $db_id;

	$query="select * from chat_s";
	$result=mysqli_query($db_id, $query);
	$chat_s=array(); for ($i=0; $row=mysqli_fetch_row($result); $i++) $chat_s[$i]=$row;
	return $chat_s;
}

function update_room($a, $ri, $rn)
{
	global $db_id;

	switch ($a)
	{
		case 1: $query="insert into chat_s (name) values ('".$rn."')"; break;
		case 2: $query="update chat_s set name='".$rn."' where id=".$ri; break;
		case 3: $query="delete from chat_s where id=".$ri; break;
		default: ;
	}
	mysqli_query($db_id, $query);
}
//end of chat functions
?>
